RxJava2: onComplete 没有用 flatMapIterable 调用

RxJava2: onComplete not called with flatMapIterable

这是一小段代码:

    val subject = BehaviorSubject.createDefault(emptyList<Int>())
    subject.onNext(Arrays.asList(1, 2, 3))
    subject.flatMapIterable { list: List<Int> -> list }
            .subscribeBy(
                    onNext = { l("on next", it) },
                    onComplete = { l("on complete") }
            )

为什么onComplete不在这里打电话?我应该如何处理这段代码?因为在原始代码中我不能使用 .toList() 方法。

你的 BehaviorSubject 形式是一个无限源,除非在它上面调用 onComplete。因此 flatMapIterable 将不会完成,您的 onComplete 处理程序将永远不会被调用。

所以要么你完成 BehaviorSubject:

val subject = BehaviorSubject.createDefault(emptyList<Int>())
subject.onNext(Arrays.asList(1, 2, 3))
subject.flatMapIterable { list: List<Int> -> list }
       .subscribeBy(
                onNext = { l("on next", it) },
                onComplete = { l("on complete") }
       )

subject.onComplete() // <-----------------------------------------------------

或者你最多拿走一件

val subject = BehaviorSubject.createDefault(emptyList<Int>())
subject.onNext(Arrays.asList(1, 2, 3))
subject.take(1) // <----------------------------------------------------------
       .flatMapIterable { list: List<Int> -> list }
       .subscribeBy(
                onNext = { l("on next", it) },
                onComplete = { l("on complete") }
       )