Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
RxSwift跳过事件,直到自己的序列完成_Swift_Rx Swift_Reactivex - Fatal编程技术网

RxSwift跳过事件,直到自己的序列完成

RxSwift跳过事件,直到自己的序列完成,swift,rx-swift,reactivex,Swift,Rx Swift,Reactivex,我有一个可观测的(我们称之为触发器)可以在短时间内发射多次。当它发出时,我正在执行一个网络请求,并将结果存储在扫描操作员处 我的问题是,我想等到请求完成后再做一次。(但现在的情况是,如果触发器发出2个可观测值,则无论fetchData是否已完成,它都会再次执行) 奖励:我还想每X秒只取第一个(去盎司不是解决方案,因为它可以一直发射,我想每X秒得到1个,这也不是节流,因为如果一个可观测的发射速度真的快了2倍,我会得到第一个和第二个延迟的X秒) 守则: trigger.flatMap { [unow

我有一个可观测的(我们称之为触发器)可以在短时间内发射多次。当它发出时,我正在执行一个网络请求,并将结果存储在扫描操作员处

我的问题是,我想等到请求完成后再做一次。(但现在的情况是,如果触发器发出2个可观测值,则无论fetchData是否已完成,它都会再次执行)

奖励:我还想每X秒只取第一个(去盎司不是解决方案,因为它可以一直发射,我想每X秒得到1个,这也不是节流,因为如果一个可观测的发射速度真的快了2倍,我会得到第一个和第二个延迟的X秒)

守则:

trigger.flatMap { [unowned self] _ in
        self.fetchData()
        }.scan([], accumulator: { lastValue, newValue in
        return lastValue + newValue
    })
和获取数据:

func fetchData() -> Observable<[ReusableCellVMContainer]>

对不起,我误解了你在下面的回答中想要达到的目的

将实现您想要的操作的操作符是
flatMapFirst
。这将忽略触发器中的事件,直到
fetchData()
完成

trigger
    .flatMapFirst { [unowned self] _ in
        self.fetchData()
    }
    .scan([], accumulator: { lastValue, newValue in
        return lastValue + newValue
    })
我在下面留下我以前的答案,以防万一(如果有的话,它有“奖金”答案。)


你遇到的问题被称为“背压”,即当被观察者产生的值比观察者能处理的要快时

在这种情况下,我建议您不要限制数据提取请求,而是将每个请求映射到一个键,然后按顺序发出数组:

trigger
    .enumerated()
    .flatMap { [unowned self] count, _ in
        Observable.combineLatest(Observable.just(count), self.fetchData())
    }
    .scan(into: [Int: Value](), accumulator: { lastValue, newValue in
        lastValue[newValue.0] = newValue.1
    })
    .map { $0.sorted(by: { $0.key < $1.key }).map { $0.value }}
trigger
    .enumerated()
    .flatMap { [unowned self] count, _ in
        Observable.combineLatest(Observable.just(count), self.fetchData())
    }
    .scan(into: [Int: Value](), accumulator: { lastValue, newValue in
        lastValue[newValue.0] = newValue.1
    })
    .map { $0.sorted(by: { $0.key < $1.key }).map { $0.value }}
extension ObservableType {
    func enumerated() -> Observable<(Int, E)> {
        let shared = share()
        let counter = shared.scan(0, accumulator: { prev, _ in return prev + 1 })
        return Observable.zip(counter, shared)
    }
}
trigger.buffer(timeSpan: seconds, count: Int.max, scheduler: MainScheduler.instance)
    .map { $0.first }