DEV Community

amay077
amay077

Posted on • Edited on

RxJava combineLatest quick example by Kotlin

RxJava's combineLatest is very convenient but I can use it difficultly because it has many overloads.
So I wrote the code snippet for combineLatest.

val name = PublishSubject.create<String>()
val age = PublishSubject.create<Int>()

// Can not omit Type parameters and BiFunction 
Observable.combineLatest<String, Int, String>(
        name, age, BiFunction { n, a -> "$n - age:${a}" })
        .subscribe({
            Log.d("combineLatest", "onNext - ${it}")
        })

// If you introduce RxKotlin then you can use type inference
Observables.combineLatest(name, age) { n, a -> "$n - age:${a}" }
        .subscribe({
            Log.d("combineLatest", "onNext - ${it}")
        })

// Also we can use Observable array for 1st parameter 
// but second parameter to be array, it's not cool.
Observable.combineLatest(arrayOf(name, age), {
    val n = it[0] as String
    val a = it[1] as Int
    "$n - age:${a}" })
        .subscribe({
            Log.d("combineLatest", "onNext - ${it}")
        })


name.onNext("saito")
age.onNext(24)
name.onNext("yoshida")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)