LoginSignup
3
1

More than 5 years have passed since last update.

RxJava(Kotlin)で通知内容が不要な通知にはUnitを使うと良いと思う

Last updated at Posted at 2018-10-23

表題通りです。RxJavaを使っていると、通知はしたいのですが、通知内容自体に関心がない場合、

Observable.just(true).subscribe(::println)

などして、「別にBoolean情報を通知したい訳じゃないんだけどなー」と内心思いながらお茶を濁してました。こんなときにUnitが使えるのですね。

Observable.just(Unit).subscribe(::println)

出力結果は以下のようになります。

kotlin.Unit

Unitって何だろうと、みてみると、

package kotlin

/**
 * The type with only one value: the Unit object. This type corresponds to the `void` type in Java.
 */
public object Unit {
    override fun toString() = "kotlin.Unit"
}

と定義されてました。なるほど。

最後に、PublishSubjectでUnit使ったコードをのせておきます。

val ps = PublishSubject.create<Unit>()
ps.subscribe(::println)
ps.onNext(Unit)
ps.onNext(Unit)
ps.onNext(Unit)
ps.onComplete()

出力結果は、

kotlin.Unit
kotlin.Unit
kotlin.Unit

です。

3
1
0

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
3
1