使用flatMap后,Rx swift保持原始流的原始顺序

时间:2017-10-16 17:05:42

标签: reactive-programming rx-swift

我试图在中间应用flatMap后将原始顺序保留在流中。

这是详细说明我的意思的图表:

---- 2-4-1 ------------------(原始流)

----------- 1--2 --------- 4--(网络活动 - 由flatMap代表延迟)

--------------- 2 --------- 4-1(想要的结果)

这是一个详细阐述情况的代码:

    persistMessageEventBus.flatMap({ num -> Observable<Int> in

        print("aaab Doing \(num)")

        let t2g = Observable.just(num).delay(Double(num), scheduler: MainScheduler.instance).do(onNext:{ num in print("aaab Done async \(num)")})

        return t2g

    }).concatMap({ num -> Observable<Int> in

        print("aaab Done map \(num)")

        return Observable.just(num)

    }).subscribe(onNext: { num in

        print("aaab done \(num)")

    }).addDisposableTo(disposeBag)

    persistMessageEventBus.onNext(2)
    persistMessageEventBus.onNext(4)
    persistMessageEventBus.onNext(1)

输出结果为:

aaab Doing 2
aaab Doing 4
aaab Doing 1
aaab Done async 1
aaab Done map 1
aaab done 1
aaab Done async 2
aaab Done map 2
aaab done 2
aaab Done async 4
aaab Done map 4
aaab done 4

想要的输出是:

aaab Doing 2
aaab Doing 4
aaab Doing 1
aaab Done async 1
aaab Done async 2
aaab Done map 2
aaab done 2
aaab Done async 4
aaab Done map 4
aaab done 4
aaab Done map 1
aaab done 1

在RxSwift中有类似的东西吗?

1 个答案:

答案 0 :(得分:1)

使用.concatMap()代替,它保证原始订单。

更新#1

然后显然它需要索引和一些缓冲。

public function addToCart($sku, $itemPrice, $itemCost, $itemName, $itemColor .... ) {}

public function addToCart($itemArray, $userArray) {}
aaab Done async 1
aaab done 2
aaab Done async 2
aaab done 4
aaab Done async 4
aaab done 1