0

I am using RxJava 2.* and I want to merge the results of two observables (one from retrofit and another from room) by using zip operator(feel free to suggest better).

Model objects that come from remote server are different from the one coming out of Room Database.

  1. I want to map the objects from Remote into that of local
  2. Merge those two results
  3. Display the result.

My remote API looks like this :

interface CategoryService{
@GET("categories")
fun getCategories(): Observable<List<Category>>

}

And my Room DAO query looks like this :

@Query("SELECT * FROM categories ORDER BY id")
abstract fun categories(): Observable<List<KmagCategory>>

I have converted Observable> into Observable> like this :

val newCategoryList : Observable<List<KmagCategory>> =settingService.getCategories().flatMap { list ->
            Observable.fromIterable(list)
                    .map { item -> KmagCategory(item.id, item.title, item.slug, item.isFav) }
                    .toList()
                    .toObservable()
        }

But when I try to zip these two observables like this :

val combinedObservable : Observable<List<KmagCategory>> = Observables.zip(KMagApp.database?.categories()?.categories()!!,newSetting)

I get Type inference failed, Expected type mismatch enter image description here

erluxman
  • 18,155
  • 20
  • 92
  • 126

2 Answers2

0

The error actually tells you that you can zip them and this produces Observable<Pair<...>>. The problem is that you assign the result to a wrong type. This is like saying "I can't add Ints" in val x: String = 1 + 2: of course you can, but the result is not a String.

You need to use zipWith and specify how to merge the values.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

I had done three Mistakes :

  1. Used Observables.zip() instead of Observable.zip()

  2. Did not tell how to zip them.

  3. Room DAO does not understand Observable so use Flowable.

So to zip those two observables I did :

val combinedObservable = Observable
    .zip(KMagApp.database?.categories()?.categories()?.toObservable(), newSetting, 
    BiFunction<List<KmagCategory>, List<KmagCategory>, List<KmagCategory>> 
    { s1, s2 -> getCombinedList(s1, s2) })
erluxman
  • 18,155
  • 20
  • 92
  • 126