简体   繁体   English

如何避免Java中的回调地狱?

[英]How to avoid callback hell in Java?

I have java app with sequence of api calls (I'm using retrofit). 我有一个带有api调用序列的java应用程序(我正在使用改造)。 Currently it looks like 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 callback hell? 是否有一些图书馆可以避免回调地狱? like TwoStep or Q in javascript. 像在JavaScript中的TwoStep或Q.

Using lambda expressions will get rid of this kind of callback hell.But, since Callback<T> interface consists of 2 abstract methods, you cannot directly use lambdas. 使用lambda expressions将摆脱这种回调地狱。但是,由于Callback<T>接口由2个抽象方法组成,因此不能直接使用lambdas。 This is where RxJava kicks in. RxJava introduces more functional way and enables you to use functional interfaces where you can use lambda to reduce callback hell. 这就是RxJava的用武之地.RxJava引入了更多功能方式,使您能够使用功能接口,您可以使用lambda来减少回调地狱。

RxJava is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences... RxJava是ReactiveX(Reactive Extensions)的Java VM实现:一个通过使用可观察序列来编写异步和基于事件的程序的库...

Here is some resources about RxJava and lambda. 这里有一些关于RxJava和lambda的资源。

As long as you are sequencing just the API calls, you can employ Retrofit's RxJava support by using Observables instead of callbacks and tying them together with the Rx stream support. 只要您只对API调用进行排序,就可以使用Observables而不是回调来使用Retrofit的RxJava支持,并将它们与Rx流支持结合在一起。 I mostly use .flatmap() function to convert result of one API call to another. 我主要使用.flatmap()函数将一个API调用的结果转换为另一个。 In your case, it would like something like this: 在你的情况下,它会像这样:

First I will be using the Observable version of the calls instead of the ones with callbacks, which will be: 首先,我将使用Observable版本的调用而不是具有回调的调用,这将是:

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

After we have these two functions in our API, we can tie them together with RxJava streams. 在我们的API中有这两个函数之后,我们可以将它们与RxJava流绑定在一起。 Here is one without error checking, I am writing 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); 
    });
}

You can now observe and subscribe to the returned Observable of this function as normal, after learning RxJava a bit: 在学习了RxJava之后,您现在可以正常观察和订阅此函数的返回Observable:

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.
                 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM