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

时间:2015-10-04 07:09:40

标签: swift system.reactive flatmap

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

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

1 个答案:

答案 0 :(得分:2)

通过深入研究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
    }
}