为什么range()和sequenceOf()在RxSwift中与flatMap的行为不同?



我是Swift和ReactiveX的新手。我觉得理解flatMap很困难。在学习flatMap的测试中,我分别使用range()和sequenceOf()来创建可观察对象。但是为什么输出出乎意料地不同,如下所示:

import RxSwift

let sequenceInt = sequenceOf(1,2,3)
let rangeInt = range(1,3)

print( " ---- expects:  [[1],[1,2],[1,2,3]] " )
print (" ---- hence: [1,1,2,1,2,3]")

print(" ---- sequenceOf misbehaving ----")
sequenceInt.flatMap { i in range( 1, i) }.subscribe { print($0) }
print(" ---- range behaves as expected ----")

rangeInt.flatMap { i in range( 1, i) }.subscribe { print($0) }

输出:

 ---- expects:  [[1],[1,2],[1,2,3]] 
 ---- hence: [1,1,2,1,2,3]
 ---- sequenceOf misbehaving ----
Next(1)
Next(1)
Next(1)
Next(2)
Next(2)
Next(3)
Completed
 ---- range behaves as expected ----
Next(1)
Next(1)
Next(2)
Next(1)
Next(2)
Next(3)
Completed

通过深入研究RxSwift的源代码,我想我找到了原因。sequenceOf()一次发出它的所有元素,而range()使用调度程序。

...
public func sequenceOf<E>(elements: E ...) -> Observable<E> {
    return AnonymousObservable { observer in
        for element in elements {
            observer.on(.Next(element))
        }
        observer.on(.Completed)
        return NopDisposable.instance
    }
}

相关内容

  • 没有找到相关文章

最新更新