LoginSignup
15
9

More than 5 years have passed since last update.

RxJava の combineLatest のコード例

Last updated at Posted at 2017-11-28

RxJava の combineLatest、overload がたくさんあって一発で書けた試しがないので、うまく書けた例を置いておきます。

nameage のいずれかの Observable<T> が変化したときに、 "name - 歳:age" な文字列を push するというものです。

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

// 型引数指定と BiFunction は省略できないみたい
Observable.combineLatest<String, Int, String>(
        name, age, BiFunction { n, a -> "$n - 歳:${a}" })
        .subscribe({
            Log.d("combineLatest", "onNext - ${it}")
        })

// RxKotlin を導入すると型推論が効くとコメントで教えてもらいました
Observables.combineLatest(name, age) { n, a -> "$n - 歳:${a}" }
        .subscribe({
            Log.d("combineLatest", "onNext - ${it}")
        })

// Observable<T> を配列で渡せるけど、第2引数の combiner が Any な配列になっちゃう
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")
15
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9