varmashrivastava
varmashrivastava

Reputation: 442

Adavantage of Retrofit with RxJava externally

AFAAIK, Retrofit uses RxJava internally.Then what is the advantage of integrating Retrofit with RxJava externally like here, if I don't want to filter,sort or modify the data received from api?Does it reduces the time for fetching response from api?In what way does it helps in improving performance of our api calls?

Upvotes: 0

Views: 772

Answers (1)

trocchietto
trocchietto

Reputation: 2617

Retrofit started as project before RxJava and you used to retrieve the API via callbacks. Then came RXJava and a more strict integration between the two was possible. So that you change Call<T> with an Observable/Flowable interface, and instead to use a call back into the code you retrieve the result directly exploiting the power of the reactive paradigm.

Please consider you have to specify you are using RXJava when you build Retrofit

Retrofit retrofit = new Retrofit.Builder()  
.baseUrl(baseUrl);
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//here
.addConverterFactory(GsonConverterFactory.create())
.build();

Saying that RXJava implements internally Retrofit is kind of tricky, Retrofit remain indipendent, just RXJava offers some binding code so that you can adapt Retrofit2 to be an Observable.

This code taken from here, explain how to bind the two

public interface UserService {  
@POST("/me")
Observable<User> me();
}

// this code is part of your activity/fragment
Observable<User> observable = userService.me();  
observable  
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribe(new Subscriber<User>() {
@Override
public void onCompleted() {
    // handle completed
}

@Override
public void onError(Throwable e) {
    // handle error
}

@Override
public void onNext(User user) {
    // handle response
}
});

Then you ask to many questions, in stackoverflow you get one reply per post. Just please consider that the advantage of using RXJava and Retrofit integrated are a lot, for instance you have a come much more clean, testable and you do not have to consider concurrency issues. Regarding the performance I get is the same for a normal case.

EDIT:

To understand better when to use RXJAVA+Retrofit and when just Retrofit you can see this post

Outside from that content please consider that is really useful to see all the succesion in a functional way inside a single class, plus you have OnComplete, you can operate any sort of transformation.

Furthermore is much easier to combine multiple calls as here, the advantages are really clear in real life situations, and also to do testing and maintain the code clean, that just taken alone these two, are two great advantages.

You also may want to explore the new Google Architecture functionalities components with Retrofit, where you can use both RXJava or LiveData

Upvotes: 3

Related Questions