[英]Using RxJava to get a distinct result with Realm and Retrofit
我知道Dan Lew幾乎回答了從不同來源獲取數據的問題,
.concat(/*...*/) .take(1)
但是如果不是從本地存儲的數據和改造中獲取用戶列表,該怎么辦?
在顯示結果(例如僅顯示不同的用戶)之前,我需要對數據進行特定於數據庫的操作。 在那種情況下,僅在網絡請求和本地數據上使用concat運算符就不會返回相同的結果。
有沒有用RxJava編寫的慣用方式?
您是否嘗試過distinct()
? 根據文檔 ,此方法將在發出時僅給您不同的對象。 如果您有自定義對象,我認為您必須實現equals()
和hashCode()
最終對我來說真正有效的方法是讓網絡請求返回RealmResult並在調用RealmQuery之前保存數據-類似於:
fun network(): Observable<RealmResult<Something>> {
return getAuth()
.andThen(somethingRepository.getRemoteSomething())
.doOnNext { somethings: List<Something> -> somethingRepository.saveSomethings(somethings) }
.flatMap { distinctSomethings }
}
val distinctSomethings: Observable<RealmResults<Something>> by lazy { getDistinctSomethings() }
//... later
fun showDistinctSomethings() {
Observable.concat(
distinctSomethings,
network()
)
.filter { somethings: RealmResults<Something> ->
somethings.toArray().isNotEmpty()
}
.take(1)
.subscribe(/*..show distinct somethings here.*/)
}
但至關重要的是,您可以用任何復雜的Realm查找替換getDistinctSomethings()
,並且始終可以得到正確的結果
希望這可以幫助我旁邊的人:P
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.