gpt4 book ai didi

swift - Rxswift map + 并行连接

转载 作者:可可西里 更新时间:2023-11-01 00:59:16 25 4
gpt4 key购买 nike

这个 Observable 正在执行以下操作

  • 给定一个可观察的源
  • 我们使用 map 来执行一些异步工作
  • 我们使用 concat 按顺序返回异步工作的结果

下面是返回期望的结果,但我想开始异步并行工作。

使用 Rx 的正确方法是什么?

import RxSwift

func delay(time: Int, closure: () -> Void) {
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, Int64(time * Int(NSEC_PER_SEC))),
dispatch_get_main_queue(), closure)
}

func doAsyncWork(value: Int, desc: String, time: Int) -> Observable<Int> {
return Observable.create() { (observer) -> Disposable in
print(desc)
delay(time) {
observer.onNext(value)
observer.onCompleted()
}
return NopDisposable.instance
}
}

let seq = Observable
.of(1, 2, 3, 4, 5)
.map { (n) -> Observable<Int> in
return doAsyncWork(n,
desc: "start \(n) - wait \(5 - n)",
time: 6 - n
)
}
.concat()

let sharedSeq = seq.shareReplay(0)
sharedSeq.subscribeNext { print("=> \($0)") }
sharedSeq.subscribeCompleted { print("=> completed") }

这个产品

//start 1 - wait 4
// => 1
//start 2 - wait 3
// => 2
//start 3 - wait 2
// => 3
//start 4 - wait 1
// => 4
//start 5 - wait 0
// => 5

期望的输出是

//start 1 - wait 4
//start 2 - wait 3
//start 3 - wait 2
//start 4 - wait 1
//start 5 - wait 0
// => 1
// => 2
// => 3
// => 4
// => 5

最佳答案

这似乎可行,但不确定这是最佳答案

import RxSwift

func delay(time: Int, closure: () -> Void) {
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, Int64(time * Int(NSEC_PER_SEC))),
dispatch_get_main_queue(), closure)
}

func doAsyncWork(value: Int, desc: String, time: Int) -> Observable<Int> {
return Observable.create() { (observer) -> Disposable in
print(desc)
delay(time) {
observer.onNext(value)
observer.onCompleted()
}
return NopDisposable.instance
}
}

let seq = Observable
.of(1, 2, 3, 4, 5)
.map { (n) -> Observable<Int> in
let o = doAsyncWork(n,
desc: "start \(n) - wait \(5 - n)",
time: 6 - n
).shareReplay(1)
o.subscribe()
return o.asObservable()
}
.concat()

let sharedSeq = seq.shareReplay(0)
sharedSeq.subscribeNext { print("=> \($0)") }
sharedSeq.subscribeCompleted { print("=> completed") }

关于swift - Rxswift map + 并行连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37758051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com