How to avoid hell callback in java?

I have a java application with api call sequence (I am using a modification). Currently it looks like a pyramid:

mApi.login(request, new Callback<LoginResponse>() { @Override public void success(LoginResponse s, Response response) { mApi.getRoutes(request, new Callback<RoutesResponse>() { @Override public void success(RoutesResponses, Response response) { ... } @Override public void failure(RetrofitError error) {} } } @Override public void failure(RetrofitError error) {} }); 

Are there some libraries to avoid hell callback? e.g. TwoStep or Q in javascript.

+6
source share
2 answers

Using lambda expressions will save you from this type of callback. But since the Callback<T> interface consists of 2 abstract methods, you cannot directly use lambdas. This is where RxJava begins to play. RxJava introduces a more functional way and allows the use of functional interfaces where you can use lambda to reduce the callback addon.

RxJava is an implementation of Java VM ReactiveX (Reactive Extensions): a library for compiling asynchronous and event-based programs using observable sequences ...

Here are some resources about RxJava and lambda.

+4
source

While you are only making API calls, you can use the Retrofit RxJava support by using Observables instead of callbacks and linking them together with Rx thread support. I mainly use the .flatmap () function to convert the result of one API call to another. In your case, it will look something like this:

First, I will use the version of Observable calls instead of those that have callbacks that will be:

 Observable<LoginResponse> login(loginRequest); Observable<RoutesResponse> getRoutes(routesRequest); 

After we have these two functions in our API, we can link them together with RxJava threads. Here is one without error checking, I write this on the go to show as a quick example:

 public Observable<RoutesResponse> rxGetRoutes(loginRequest, routesRequest) { final YourAPI mAPI = YourApiProvider.getInstance(); return mAPI.login(loginRequest) //using flatmap to convert one answer to another answer .flatmap( (Func1) LoginResponse -> { return mAPI.getRoutes(routesRequest); }); } 

Now you can observe and subscribe to the returned Observable of this function as usual, after learning RxJava:

 rxGetRoutes(loginReq, routesReq) .observeOn(//the thread you want to observe on) .subscribe( new Subscriber<RoutesResult>() { @Override //the functions of Subscriber you need to override //where you can also check for errors //Check RxJava documentation after your IDE completes this area. }); 
+2
source

Source: https://habr.com/ru/post/984420/


All Articles