2016-10-28 57 views
0

我有方法返回Place的對象,但首先我必須檢查Place對象是否存在於數據庫中,然後返回他或以其他方式從休息服務中獲取Place對象。如何最簡單的方法我可以檢查出來?如何比較Observable的結果並返回其中一個

public Observable<Place> getPlace(final String id) { 

    // Both method from repository and rest are: Observable<Place> getPlace(String id); 

    // if placeDatabaseRepository.getPlace(id) != null then: 
    return placeDatabaseRepository.getPlace(id); 
    // else Place == NULL then: 
    return placeRest.getPlace(id); 
} 
+0

的【什麼是RxJava相當於否則容易的(可能的複製http://stackoverflow.com/questions/32833705/what-is-rxjava-equivalent-of-orelse) –

+0

你可以在你的可觀察值上使用'switchIfEmpty'運算符 – nnesterov

回答

1

Dan Lew寫道an excellent article關於這個問題。

它的要點是你使用兩個Observable<Place>實例 - 如果它不是null,則返回數據庫的結果,另一個從REST調用返回結果。你與concat()運營商把它們結合在一起,只需要與運營商first()第一發射項目,有點像這樣:

Observable<Place> dbSource = Observable 
    .just(placeDatabaseRepository.getPlace(id)) 
    .filter(place -> place != null); 
Observable<Place> restSource = Observable 
    .just(placeRest.getPlace(id)); 

return Observable 
    .concat(dbSource, restSource) 
    .first(); 
+1

這篇文章建議使用concat observable的第一個(條件)。您的代碼片段將過濾器應用於數據庫observable。這種變化的原因是什麼?我在博客文章中使用了該方法,當數據庫爲空時(剩下的observable沒有運行),它就無法工作。你的建議在這裏會起作用。 – Francesc

+0

嗯,這很令人費解。我在數據庫源代碼中編寫了過濾器作爲首選項 - 我甚至沒有假設它會有所作爲......這需要一些調試。 – npace

+1

如果placeDatabaseRepository爲空,您將得到一個NPE,該NPE不會傳遞到鏈中。也許使用像Object.requireNonNull(placeDatabaseRepository)之類的東西,並刪除空過濾器。如果你在流水線中得到「null」,那麼只需要空過濾器。對於「getPlace」方法,我會使用超時。如果其中一個觀察對象沒有產生價值/沒有完成,你會永遠阻止。 –

相關問題