不知道为什么,万一我showcaseFlatMap
用以下代码调用方法:
fun showcaseFlatMap() {
val colors: Flowable<String> = Flowable.just("orange", "red", "green")
.flatMap<String> { colorName -> simulateRemoteOperation(colorName) }
colors.subscribe { value -> println("Subscriber received: {$value}") }
}
fun simulateRemoteOperation(color: String): Flowable<String> {
return Flowable.intervalRange(1, color.length.toLong(), 0, 200, TimeUnit.MILLISECONDS)
.map { iteration -> color + iteration }
}
我得到以下结果:
Subscriber received: {orange1}
Subscriber received: {red1}
Subscriber received: {green1}
Subscriber received: {orange2}
Subscriber received: {red2}
Subscriber received: {green2}
Subscriber received: {orange3}
Subscriber received: {red3}
Subscriber received: {green3}
Subscriber received: {orange4}
Subscriber received: {green4}
Subscriber received: {orange5}
Subscriber received: {green5}
Subscriber received: {orange6}
但是,如果我更改此方法中的代码:
val colors: Flowable<String> = Flowable.just("orange", "red", "green")
.flatMap<String> { colorName -> simulateRemoteOperation(colorName) }
编码:
val colors: Flowable<String> = Flowable.just("orange", "red", "green")
colors.flatMap<String> { colorName -> simulateRemoteOperation(colorName) }
结果完全不同:
Subscriber received: {orange}
Subscriber received: {red}
Subscriber received: {green}
造成这种结果变化的原因是什么?我预计输出不会改变。
因为
flatMap
,实际上,所有运算符都会返回一个Flowable
您忽略的新对象(在这种情况下),而不是更改当前对象的状态。事实证明,您只订阅Flowable.just("orange", "red", "green")