nmu
nmu

Reputation: 1519

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

.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.

Is there any idiomatic way of writing this with RxJava?

Upvotes: 0

Views: 164

Answers (2)

nmu
nmu

Reputation: 1519

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:

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

Hope this helps someone beside me :P

Upvotes: 0

Cătălin Florescu
Cătălin Florescu

Reputation: 5158

Have you tried 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()

Upvotes: 1

Related Questions