android - ZIP 运算符不适用于 PublishSubject,我做错了什么?
问题描述
我是 RxJava 的新手,无法意识到 - 为什么当我使用两个 PublishSubject 时,我的“压缩”可观察对象不会发出项目?(据我所知 ZIP 运营商应该将两个流“合并”为一个)
val currentSubject = PublishSubject.create<Int>()
val maxSubject = PublishSubject.create<Int>()
currentSubject.onNext(1)
maxSubject.onNext(2)
currentSubject.onNext(1)
maxSubject.onNext(2)
Log.d("custom", "BINGO!")
val zipped = Observables.zip(currentSubject, maxSubject) { current, max -> "current : $current, max : $max " }
zipped.subscribe(
{ Log.d("custom", it) },
{ Log.d("custom", "BONGO!") },
{ Log.d("custom", "KONGO!") }
)
currentSubject.onComplete()
maxSubject.onComplete()
我期待这些项目出现在“{ Log.d("custom", it) }" 函数中,但它没有发生。我做错了什么?
编译后的日志:
2019-06-25 22:25:36.802 3631-3631/ru.grigoryev.rxjavatestdeleteafter D/custom: BINGO!
2019-06-25 22:25:36.873 3631-3631/ru.grigoryev.rxjavatestdeleteafter D/custom: KONGO!
解决方案
这里的问题不在于您的zip
实现,而在于 a 的默认行为PublishSubject
。但首先,让我们备份
冷热观测
在 Rx 中,有和两种类型。最常见的类型是可观察的。一个可观察对象在被调用之前不会开始发射值。Obervables
hot
cold
cold
cold
.subscribe()
val obs = Observable.fromIterable(listOf(1, 2, 3, 4);
obs.subscribe { print(it) }
// Prints 1, 2, 3, 4
hot
无论观察者是否订阅了 observable,它都会发出值。
val subject = PublishSubject.create<Int>()
subject.onNext(1)
subject.onNext(2)
subject.subscribe { print(it) }
subject.onNext(3)
subject.onNext(4)
// Prints 3, 4
注意未打印的方式1
和位置。2
这是因为 aPublishSubject
是一个hot
可观察的1
并且2
在它被订阅之前发出。
回到你的问题
在您的示例中,您的发布主题在订阅之前发出 1 和 2。要zipped
一起查看它们,请移动您的代码。
val currentSubject = PublishSubject.create<Int>()
val maxSubject = PublishSubject.create<Int>()
Log.d("custom", "BINGO!")
val zipped = Observables.zip(currentSubject, maxSubject) { current, max -> "current : $current, max : $max " }
zipped.subscribe(
{ Log.d("custom", it) },
{ Log.d("custom", "BONGO!") },
{ Log.d("custom", "KONGO!") }
)
currentSubject.onNext(1)
maxSubject.onNext(2)
currentSubject.onNext(1)
maxSubject.onNext(2)
currentSubject.onComplete()
maxSubject.onComplete()
推荐阅读
- c++ - 如何使用不同的参数多次调用函数?
- bash - 如何在centos 7中递归打开文件.txt
- python - For 循环、条件语句、计数
- java - 为什么当我更改静态文件并重新加载页面时 spring devtools 不起作用?
- c# - c#实体框架循环遍历记录savechanges()错误
- django - 来自不同模型的图像字段的 Django GET API
- c# - 为什么是 GetHostEvidence
() 返回 null 而不是预期的 StrongName? - reactjs - React Native 添加顶部细标题
- square-connect - 方形连接。Square-checkout 收款电话号码
- angular - 以编程方式更改 NbStepper ngx/admin