I want to do GET request with Retrofit, but I don't know on which layer of MVP pattern I need to do it. As I know, Model sends all data to Presenter, and then, Presenter shows data on View. So, I thought that the best place is Model. But how Presenter will know that Model fetched all data already and ready to pass it to Presenter? For this, I think I need to use interface that notifies Presenter when Model has finished loading data. But googling what is the best way, I saw that developers use something like Repositories and Managers. But I couldn't figure out the role of each of them. So, how to solve the problem? What is the best place to create HTTP requests in MVP pattern? If it is Model, what is the best way to send all data to Presenter?
What you need is a callback structure from you model to the presenter. What I normally use and recommend is to use RxJava, retrofit2 already has an option for returning an Observable object which makes everything much easier.
Let's say you have an endpoint like this one, this is a retrofit response that returns an observable:
@Headers({"Content-Type: application/json", "Accept: application/json"})
@GET("/api/v1/banners")
Observable<Response<GetBannersResponse>> getBanners(
@Header("Authorization") String auth_token);
The GetBannersResponse class is just a POJO to encapsulate my json response:
public class GetBannersResponse {
List<Banner> banners;
public List<Banner> getBanners() {
return banners;
}
public void setBanners(List<Banner> banners) {
this.banners = banners;
}
}
My Model (interactor) class I like to call DataHandler looks like this:
public class MyDataHandler implements MyDataHandlerContract.DataHandler {
private RetrofitAPI theCloud;
private PreferencesUtil prefs;
@Inject
public CatalogDataHandler(TaskrAPIConfig theCloud, PreferencesUtil prefs) {
this.theCloud = theCloud;
this.prefs = prefs;
}
@Override
public Observable<Response<GetBannersResponse>> getBanners() {
return theCloud.getApiService().getBanners(prefs.getTokenFormatted());
}
}
You can see that I'm returning the observable from the Retrofit call. Then in my presenter I just subscribe to this observable and act accordingly:
@Override
public void getBanners() {
dataHandler
.getBanners()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Response<GetBannersResponse>>() {
@Override
public void onCompleted() {
//act on complete
}
@Override
public void onError(Throwable e) {
//act on error
}
@Override
public void onNext(Response<GetBannersResponse> getBannersResponseResponse) {
//act on result received
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With