2016-08-04 66 views
1

對於以下場景,什麼是正確的RxJava運算符:什麼是正確的RxJava運營商做到這一點?

我想檢查是否有令牌存儲,如果沒有從網絡獲取並使用它來執行另一個網絡請求。

我認爲這應該與and/then/whenfilterflatMap的組合完成,但不知道如何。

+0

還要注意的是'cache'可以成爲一個網絡的高速緩存有助於觀察到的請求例。 –

回答

2

有很多方法可以解決這個問題。另一種通用解決方案是Observable.concat

// Our sources (left as an exercise for the reader) 
Observable<Data> memory = ...; 
Observable<Data> disk = ...; 
Observable<Data> network = ...; 

// Retrieve the first source with data 
Observable<Data> source = Observable 
    .concat(memory, disk, network) 
    .first(); 

您將需要兩個observables爲您的情況。如果令牌存在於本地存儲器concat中,則不會訂閱網絡可觀察值。更多信息在博客文章。

代碼示例this blog post

1

我不知道如果這是您尋找的是,但結構應該很簡單

Observable.just(getToken()) 
     .filter(token->Strings.isNullOrEmpty(token)) 
     .map(this::findNewToken) 
     .cache() 
     .subscribe(token -> println("Your new Token") 
相關問題