简体   繁体   English

使用RxJava通过Realm和Retrofit获得不同的结果

[英]Using RxJava to get a distinct result with Realm and Retrofit

I know that Dan Lew pretty much answered the question of getting data from different sources with a 我知道Dan Lew几乎回答了从不同来源获取数据的问题,

.concat(/*...*/) .take(1)

But what if instead of getting a List of users from both my locally stored data and retrofit. 但是如果不是从本地存储的数据和改造中获取用户列表,该怎么办?

I needed to do a database specific operation on the data before displaying the result like showing distinct users only. 在显示结果(例如仅显示不同的用户)之前,我需要对数据进行特定于数据库的操作。 In that case simply using the concat operator on both my network request and local data wouldn't return the same result. 在那种情况下,仅在网络请求和本地数据上使用concat运算符就不会返回相同的结果。

Is there any idiomatic way of writing this with RxJava? 有没有用RxJava编写的惯用方式?

Have you tried distinct() ? 您是否尝试过distinct() According documentation , this method will give you only different object when they are emitted. 根据文档 ,此方法将在发出时仅给您不同的对象。 If you have custom objects, i think you must implement equals() and hashCode() 如果您有自定义对象,我认为您必须实现equals()hashCode()

What ended up working really well for me is having the network request return a RealmResult and saving the data just before calling the RealmQuery - so something like: 最终对我来说真正有效的方法是让网络请求返回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.*/)
}

Crucially though, you could replace getDistinctSomethings() with any complex Realm look up and you would always get the right result 但至关重要的是,您可以用任何复杂的Realm查找替换getDistinctSomethings() ,并且始终可以得到正确的结果

Hope this helps someone beside me :P 希望这可以帮助我旁边的人:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM