[英]How to avoid callback hell in Java?
我有一個帶有api調用序列的java應用程序(我正在使用改造)。 目前它看起來像金字塔:
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) {}
});
是否有一些圖書館可以避免回調地獄? 像在JavaScript中的TwoStep或Q.
使用lambda expressions
將擺脫這種回調地獄。但是,由於Callback<T>
接口由2個抽象方法組成,因此不能直接使用lambdas。 這就是RxJava的用武之地.RxJava引入了更多功能方式,使您能夠使用功能接口,您可以使用lambda來減少回調地獄。
RxJava是ReactiveX(Reactive Extensions)的Java VM實現:一個通過使用可觀察序列來編寫異步和基於事件的程序的庫...
這里有一些關於RxJava和lambda的資源。
只要您只對API調用進行排序,就可以使用Observables而不是回調來使用Retrofit的RxJava支持,並將它們與Rx流支持結合在一起。 我主要使用.flatmap()函數將一個API調用的結果轉換為另一個。 在你的情況下,它會像這樣:
首先,我將使用Observable版本的調用而不是具有回調的調用,這將是:
Observable<LoginResponse> login(loginRequest);
Observable<RoutesResponse> getRoutes(routesRequest);
在我們的API中有這兩個函數之后,我們可以將它們與RxJava流綁定在一起。 這是一個沒有錯誤檢查的,我正在寫這個以顯示為一個簡單的例子:
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);
});
}
在學習了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.