Tuesday, April 19, 2016

RxJava/Retrofit - How can I force users to use a specific subclass of Subscriber?

Leave a Comment

Before using rx.Observable, I used a custom callback with retrofit so I can add some specific logic for handling response/error and not have to do that inside the callback for every request as boilerplate code.

I force users to use the custom callback by putting it in the method signature like this:

@GET("/user_endpoint/") void getUser(CustomCallback<User> callback);  @GET("/profile_endpoint/") void getProfile(CustomCallback<Profile> callback); 

but now that I'm returning an Observable:

@GET("/user_endpoint/") Observable<User> getUser();  @GET("/profile_endpoint/") Observable<Profile> getProfile(); 

I can't figure out a way to make sure that a custom callback always proxies the error/response.

Also, with retrofit2.0, how can I force the user to use a custom callback with the returned Call object?

CustomCallback for reference:

public abstract class CustomCallback<T> implements Callback<T> {    @Override public final void success(T t, Response response) {     // do some logic     onSuccess(t);   }    @Override public final void failure(RetrofitError error) {     // do something with the error here such as show a Toast     Toast.makeText(Application.getInstance(), error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();     onFailure(error);   }    public abstract void onSuccess(T response);    public abstract void onFailure(Throwable error); } 

1 Answers

Answers 1

Stop. You're thinking this the wrong way.

Instead consider this: You have the normal Retrofit interface:

interface Foo {    @GET("/user_endpoint/")    Observable<User> getUser(); } 

And then you have your decorator class:

public class FooDecorator implements Foo {     private Foo delegate = ...; // inject or create the Retrofit instance.      @Override     public Observable<User> getUser() {        return delegate.getUser().doOnNext(...).doOnError(...);     } } 

Then you use only the second class everywhere in your code (preferably just let the DI system use that) and you're set.

If you're feeling adventurous, you could even adapt the RxJavaCallAdapterFactory so that it modifies the returned observables without the need of a custom class.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment