Reputation: 1519
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
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
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