表題通りです。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
です。