简体   繁体   English

收集后订阅无效

[英]Subscribe after collect doesn't work

I'm experimenting with RxJava. 我正在尝试RxJava。 I need an Observable , which produces a HashSet<String> . 我需要一个Observable ,它产生一个HashSet<String> Into Observable I want to be abele to put Pair<String, Boolean> in the way that false boolean value removes the String key from the resulting HashSet . 进入Observable我想成为一个假人,以false布尔值从结果HashSet删除String键的方式放置Pair<String, Boolean> Here's a code snippet of what I have: 这是我所拥有的代码片段:

private val selectionSubject = ReplaySubject.create<Pair<String, Boolean>>()
init {
    selectionSubject.onNext(Pair("dd", false))
    selectionSubject
        .collect({HashSet<String>()}, {dest, value -> collectSelection(dest, value)})
        .subscribe { t1, t2 -> Log.d(TAG, t1.toString())}
}

private fun collectSelection(dest: HashSet<String>, value: Pair<String, Boolean>): HashSet<String> {
    if (value.second) {
        dest.add(value.first)
    } else {
        dest.remove(value.first)
    }
    Log.d(TAG, "collectSelection, ${dest.toString()}")
    return dest
}

In the logs I can see that collectSelection gets called but my subscribe listener doesn't. 在日志中,我可以看到调用了collectSelection ,但是没有调用我的订阅侦听器。

How can it be fixed? 如何解决?

collect waits for onComplete event from the stream above before emitting a value. 在发出值之前, collect等待上面的流中的onComplete事件。 In your case, ReplaySubject never ends and thus no value is emitted. 就您而言, ReplaySubject永远不会结束,因此不会发出任何值。

Without knowing the context of selectionSubject I can't provide a solution to your problem, like, does it have to remain open? 在不知道selectionSubject上下文的情况下,我无法为您的问题提供解决方案,例如,它必须保持开放状态吗? If there are limited onNext calls, you can use .take(X) . 如果onNext调用受到限制,则可以使用.take(X) If it has to remain open, you shouldn't depend on collect but add the item inside on HashSet in something like .doOnNext 如果必须保持打开状态,则不应该依赖collect,而应将其添加到HashSet中的.doOnNext类的.doOnNext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM