Skip to content

Instantly share code, notes, and snippets.

@bluemix
Created December 21, 2016 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluemix/86bac8e1ad0afd37f73450078faf3e16 to your computer and use it in GitHub Desktop.
Save bluemix/86bac8e1ad0afd37f73450078faf3e16 to your computer and use it in GitHub Desktop.
Retrofit with RxAndroid and Retrolambda

FooService.java

public interface FooService {
    ...
    
    @GET("allVideoInfo/id/{videoid}")
    Observable<VideoModel> getAllVideoInfo(@Path("videoid") String videoId);
    
    ...
}

FooApiManager.java

public class FooApiManager {
    private final FooService fooService;
    private static FooApiManager instance;
    private Context context;
    
    private Gson gson;
    public static OkHttpClient client;
    
    ...
  
    public static FooApiManager with(Context context) {
        if (instance == null) {
            synchronized (FooApiManager.class) {
               new FooApiManager(context);
            }
        }
        return instance;
    }
    
    private FooApiManager(Context context) {
        this.context = context;
        gson = new GsonBuilder().setLenient().create();
        if (client == null) {
            client = new OkHttpClient.Builder()
                    .build();
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://example.com/api/android/")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();

        fooService = retrofit.create(FooService.class);
        instance = this;
    }
    
    ...
  
    public Observable<VideoModel> getAllVideoInfo(String videoId) {
        return fooService
                .getAllVideoInfo(videoId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
    ...
}

FooActivity.java

...
         FooApiManager.with(getActivity())
              .getAllVideoInfo(video.getId())
              .subscribe(fullVideoModel -> {
                        ... 
               }, error -> { // MUST be handled when request fails or invalid response
                     // error.getMessage();
                     // error.printStackTrace();
                        ...
               });
...                    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment