Search code examples
kotlinrx-kotlin

RxKotlin "withLatestFrom(...)" compile error: not enough information to infer type variable R


1) The code below fails to compile with an error: "not enough information to infer type variable R"

keywordChanges
  .withLatestFrom(searchParamsSubject)
  .subscribe { (keyword, searchParams) ->
     ...
  }

2) The code below compiles and works, but I would prefer not to have an empty subscribe() and not to put side effects into the combiner function.

keywordChanges
  .withLatestFrom(searchParamsSubject) { keyword, searchParams ->
    searchParamsSubject.onNext(searchParams.copy(keyword = keyword))
  }
  .subscribe()

3) Below is the code from the RxKotlin library, that I am trying to call in 1)

/**
 * Emits a `Pair`
 */
inline fun <T, U, R> Observable<T>.withLatestFrom(other: ObservableSource<U>): Observable<Pair<T,U>>
        = withLatestFrom(other, BiFunction{ t, u -> Pair(t,u)  }

How could I modify the code in 1) to make it work?


Solution

  • You have to specifically tell the compiler what classes you are working with.

            val o1 = Observable.just(1)
            val o2 = Observable.just(2)
    
            o1.withLatestFrom(o2, BiFunction { t1 : Int, t2 : Int ->  t1 to t2})
                .subscribe { (one, two) -> }
    

    Alternatively, RxKotlin extension function library handles this for you. https://github.com/ReactiveX/RxKotlin