具有toList

时间:2018-09-20 18:30:22

标签: kotlin rx-java2

有人可以解释我如何在RxJava中通过flatMap运算符传递onComplete信号吗?

如果注释了flatMap运算符,我可以获得1到10的数字列表,这意味着toList将收到onComplete信号。但是,当我想在flatMap中进一步处理数据时,它将消耗onComplete信号,但我无法获得任何结果。如何通过flatMap运算符传递onComplete信号?

我有以下简单程序:

fun main(args: Array<String>) {
    notify()
            .flatMapMaybe { processData(it) }
            .toList()
            .subscribe(
                    { println("onNext: $it") },
                    { println("onError: ${it.message}") }
            )
}

fun notify(): Flowable<Int> {
    return Flowable.create({ emitter ->
        val random = Random()
        for (index in 1..10) {
            emitter.onNext(index)
            Thread.sleep((random.nextInt(500)).toLong())
        }
        emitter.onComplete()

    }, BackpressureStrategy.BUFFER)
}

fun processData(data: Int): Maybe<String> {
    return Maybe.fromCallable { data }
            .flatMap {
                if (it.mod(2) == 0) {
                    Maybe.fromCallable { it.toString() }
                } else {
                    Maybe.never()
                }
            }
}

1 个答案:

答案 0 :(得分:2)

使用Maybe.never()代替返回Maybe.empty()。根据文档,Maybe.empty()应该立即发布onComplete()