2016-05-02 4 views
1

私は基本的にAPIをラップするライブラリを構築しようとしています。基本的に、どのように私は換装コールバックシステムを包むでしょうRetrofitを内部的に使用し、応答をラップするライブラリを構築する

ApiService api = retrofit.create(ApiService.class); 
Call<Response> call = api.getPlaylistInfo() 
call.enqueue(new Callback<Response>() { 
    @Override 
    public void onResponse(Call<Response> call, Response<Response> response) { 
     //handle response 
    } 

    @Override 
    public void onFailure(Call<Response> call, Throwable t) { 
     //handle failure 
    } 

}); 

MySDK mySDK = new MySDK("username", "password"); 

mySDK.getPlaylistInfo("3423", 2323, new CustomCallback<>(){ 

//on response 
//on failure 

}); 

だからバニラレトロフィットで、APIの呼び出しは、通常、次のようになります。基本的には、のために行くの構造イムは、このようなものです私自身に?これを行う必要があるのは、最終応答を送信する前にAPIから返されたデータを前処理する必要があるからです。

答えて

1

それはあなたが始めるに役立つかもしれないので、私は似た何かを書いて、これはそれに似ているので、私はRetrofit2に移行するときI'vは、バレーボールのために書かれ、再使用される実装(this SO question)に従います。

グローバルオブジェクト(あなたがMySDKと呼ぶだろうか)あなたのリクエストを処理するsingeltonクラスとして作成:アプリケーションだときにinstatiateシングルトンクラスを作成

がアップします:

public class NetworkManager 
{ 
    private static final String TAG = "NetworkManager"; 
    private static NetworkManager instance = null; 

    private static final String prefixURL = "http://some/url/prefix/"; 

    //for Retrofit API 
    private Retrofit retrofit; 
    private ServicesApi serviceCaller; 

    private NetworkManager(Context context) 
    { 
     retrofit = new Retrofit.Builder().baseUrl(prefixURL).build(); 
     serviceCaller = retrofit.create(ServicesApi.class); 
     //other stuf if you need 
    } 

    public static synchronized NetworkManager getInstance(Context context) 
    { 
     if (null == instance) 
      instance = new NetworkManager(context); 
     return instance; 
    } 

    //this is so you don't need to pass context each time 
    public static synchronized NetworkManager getInstance() 
    { 
     if (null == instance) 
     { 
      throw new IllegalStateException(NetworkManager.class.getSimpleName() + 
        " is not initialized, call getInstance(...) first"); 
     } 
     return instance; 
    } 

    public void somePostRequestReturningString(Object param1, final SomeCustomListener<String> listener) 
    { 
     String url = prefixURL + "this/request/suffix"; 

     Map<String, Object> jsonParams = new HashMap<>(); 
     jsonParams.put("param1", param1); 

     Call<ResponseBody> response; 
     RequestBody body; 

     body = RequestBody.create(okhttp3.MediaType.parse(JSON_UTF), (new JSONObject(jsonParams)).toString()); 
     response = serviceCaller.thePostMethodYouWant("someUrlSufix", body); 

     response.enqueue(new Callback<ResponseBody>() 
     { 
      @Override 
      public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> rawResponse) 
      { 
       try 
       { 
        String response = rawResponse.body().string(); 

        // do what you want with it and based on that... 
        //return it to who called this method 
        listener.getResult("someResultString"); 
       } 
       catch (Exception e) 
       { 
       e.printStackTrace(); 
       listener.getResult("Error1..."); 
       } 
      } 
      @Override 
      public void onFailure(Call<ResponseBody> call, Throwable throwable) 
      { 
       try 
       { 
       // do something else in case of an error 
       listener.getResult("Error2..."); 
       } 
       catch (Exception e) 
       { 
       throwable.printStackTrace(); 
       listener.getResult("Error3..."); 
       } 
      } 
     }); 
    } 

    public void someGetRequestReturningString(Object param1, final SomeCustomListener<String> listener) 
    { 
     // you need it all to be strings, lets say id is an int and name is a string 
     Call<ResponseBody> response = serviceCaller.theGetMethodYouWant 
      (String.valueOf(param1.getUserId()), param1.getUserName()); 

     response.enqueue(new Callback<ResponseBody>() 
     { 
      @Override 
      public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> rawResponse) 
      { 
       try 
       { 
        String response = rawResponse.body().string(); 

        // do what you want with it and based on that... 
        //return it to who called this method 
        listener.getResult("someResultString"); 
       } 
       catch (Exception e) 
       { 
       e.printStackTrace(); 
       listener.getResult("Error1..."); 
       } 
      } 
      @Override 
      public void onFailure(Call<ResponseBody> call, Throwable throwable) 
      { 
       try 
       { 
       // do something else in case of an error 
       listener.getResult("Error2..."); 
       } 
       catch (Exception e) 
       { 
       throwable.printStackTrace(); 
       listener.getResult("Error3..."); 
       } 
      } 
     }); 
    } 
} 

これはあなたのインターフェイスで動作します(POSTで例とリクエストをGET、GETのparamsせずにすることができる):

public interface BelongServicesApi 
{ 
    @POST("rest/of/suffix/{lastpart}") // with dynamic suffix example 
    Call<ResponseBody> thePostMethodYouWant(@Path("lastpart") String suffix, @Body RequestBody params); 

    @GET("rest/of/suffix") // with a fixed suffix example 
    Call<ResponseBody> theGetMethodYouWant(@Query("userid") String userid, @Query("username") String username); 
} 

アプリケーションが起動したとき:

public class MyApplication extends Application 
{ 
    //... 

    @Override 
    public void onCreate() 
    { 
     super.onCreate(); 
     NetworkManager.getInstance(this); 
    } 

//... 

} 

あなたのコールバックのためのシンプルなリスナーインタフェース(別々のファイルが良いだろう):

public interface SomeCustomListener<T> 
{ 
    public void getResult(T object); 
} 

そして最後に、あなたが好きな場所から、コンテキストがそこに既にある、ちょうど呼び出し:

public class BlaBla 
{ 
    //..... 

     public void someMethod() 
     { 
      //use the POST or GET 
      NetworkManager.getInstance().somePostRequestReturningString(someObject, new SomeCustomListener<String>() 
      { 
       @Override 
       public void getResult(String result) 
       { 
        if (!result.isEmpty()) 
        { 
        //do what you need with the result... 
        } 
       } 
      }); 
     } 
} 

リスナーで任意のオブジェクトを使用して、受信する必要があるものに応じてレスポンス文字列を対応するオブジェクトに解析するだけで、どこからでも(onClicksなど)呼び出すことができますオブジェクトはメソッド間で一致する必要があります。

希望の方はこちら!

関連する問題