PublishSubject不发出项目

时间:2019-12-18 20:32:42

标签: android rx-java rx-java2 relay publishsubject

为什么下面的代码没有发出任何结果? Subject出了什么问题?我希望我订阅的那一刻会得到结果,即我声明的长度。

val subject = PublishSubject.create<String>()//PublishRelay.accept() does not work as well
subject.onNext("Alpha"
subject.onNext("Beta")
subject.onNext("Gamma")
subject.onComplete()
subject.map{ it.length }
        .subscribe { println(it) }

1 个答案:

答案 0 :(得分:3)

发布主题仅在订阅后发射项目。 如果您希望所有订阅都获得所有发射,请尝试更改为ReplaySubject,或者如果希望在订阅时获得最后的发射,请更改为BehaviourSubject。

您可以在此处详细了解不同类型的主题:

http://reactivex.io/documentation/subject.html

val subject = ReplaySubject.create<String>()/
subject.onNext("Alpha"
subject.onNext("Beta")
subject.onNext("Gamma")
subject.onComplete()
subject.map{ it.length }
    .subscribe { println(it) }

或者,订阅,然后致电onNext:

val subject = PublishSubject.create<String>()
subject.map{ it.length }
    .subscribe { println(it) }
subject.onNext("Alpha"
subject.onNext("Beta")
subject.onNext("Gamma")
subject.onComplete()