[英]RXJava2: correct pattern to chain retrofit requests
我對RXJava一般來說相對較新(實際上只開始使用它與RXJava2),我發現的大多數文檔往往是RXJava1; 我現在通常可以在兩者之間進行轉換,但整個Reactive的東西都很大,它是一個壓倒性的API,有很好的文檔(當你能找到它時)。 我正在嘗試簡化我的代碼,我想用嬰兒步驟來做。 我想要解決的第一個問題是我在當前項目中做了很多常見的模式:
您有一個請求,如果成功,您將用於發出第二個請求。
如果其中一個失敗,您需要能夠識別哪個失敗。 (主要是顯示自定義UI警報)。
這就是我現在通常這樣做的方式:
(為簡單起見,省略了.subscribeOn/observeOn
)
Single<FirstResponse> first = retrofitService.getSomething();
first
.subscribeWith(
new DisposableSingleObserver<FirstResponse>() {
@Override
public void onSuccess(final FirstResponse firstResponse) {
// If FirstResponse is OK…
Single<SecondResponse> second =
retrofitService
.getSecondResponse(firstResponse.id) //value from 1st
.subscribeWith(
new DisposableSingleObserver<SecondResponse>() {
@Override
public void onSuccess(final SecondResponse secondResponse) {
// we're done with both!
}
@Override
public void onError(final Throwable error) {
//2nd request Failed,
}
});
}
@Override
public void onError(final Throwable error) {
//firstRequest Failed,
}
});
在RXJava2中有更好的方法來處理這個問題嗎?
我已經嘗試過flatMap
和變體甚至是Single.zip
或類似的東西,但我不確定最簡單和最常見的模式是什么來處理這個問題。
如果您想知道FirstRequest將在SecondRequest中獲取我需要的實際Token
。 沒有令牌,無法發出第二個請求。
我建議使用平面地圖(如果這是一個選項,還可以使用retrolambda )。 如果你沒有對它做任何事情,你也不需要保留返回值(例如Single<FirstResponse> first
)。
retrofitService.getSomething()
.flatMap(firstResponse -> retrofitService.getSecondResponse(firstResponse.id)
.subscribeWith(new DisposableSingleObserver<SecondResponse>() {
@Override
public void onSuccess(final SecondResponse secondResponse) {
// we're done with both!
}
@Override
public void onError(final Throwable error) {
// a request request Failed,
}
});
這文章讓我覺得通過我如何總體結構RxJava風格。 如果可能,您希望鏈是一個高級操作列表,因此可以將其讀作一系列操作/轉換。
編輯沒有lambdas你可以使用Func1
作為你的flatMap。 同樣的事情只是更多的鍋爐板代碼。
retrofitService.getSomething()
.flatMap(new Func1<FirstResponse, Observable<SecondResponse> {
public void Observable<SecondResponse> call(FirstResponse firstResponse) {
return retrofitService.getSecondResponse(firstResponse.id)
}
})
.subscribeWith(new DisposableSingleObserver<SecondResponse>() {
@Override
public void onSuccess(final SecondResponse secondResponse) {
// we're done with both!
}
@Override
public void onError(final Throwable error) {
// a request request Failed,
}
});
這不適合你嗎?
retrofitService
.getSomething()
.flatMap(firstResponse -> retrofitService.getSecondResponse(firstResponse.id))
.doOnNext(secondResponse -> {/* both requests succeeded */})
/* do more stuff with the response, or just subscribe */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.