我从RestAPI获取一个数据,在收到一个值之后,我必须发送另一个网络请求,该请求有一个重要的延迟,并且对第一次获取没有影响。我想使用handleEvents
publisher operator,但这个在苹果文档的调试部分。如果我使用flatMap
,那么我的接收器将等待第二次获取的结果,但它对我的主流没有影响。有没有其他方法可以启动网络调用,而不会影响主流/管道?
示例1:这个看起来不错,但是handleEvents
在苹果文档的调试部分
cancellable = URLSession.shared.dataTaskPublisher(for: .init(string: "http://httpbin.org/delay/1")!)
.handleEvents(receiveOutput: { _ in
cancellable2 = URLSession.shared.dataTaskPublisher(for: .init(string: "http://httpbin.org/delay/10")!)
.sink(receiveCompletion: { completion in
print(completion)
}, receiveValue: { value in
print(value)
})
}
.sink { completion in
print(completion)
} receiveValue: { value in
print(value)
}
示例2:这使我的主流等待从flatMap
恢复的秒的结果,这使得我的流等待完成信号
cancellable = URLSession.shared.dataTaskPublisher(for: .init(string: "http://httpbin.org/delay/1")!)
.flatMap { _ in
URLSession.shared.dataTaskPublisher(for: .init(string: "http://httpbin.org/delay/10")!)
}
.sink { completion in
print(completion)
} receiveValue: { value in
print(value)
}
发布于 2021-11-26 06:24:31
这是其中一种方法。这样,即使第一次调用抛出错误,您也可以多次发送第一个请求。
let startFirst = PassthroughSubject<Void, Never>()
let startSecond = PassthroughSubject<Void, Never>()
let cancellable =
startFirst
.flatMap { _ in
URLSession.shared.dataTaskPublisher(for: .init(string: "http://httpbin.org/delay/1")!)
// handle errors
}
.sink { completion in
print(completion)
} receiveValue: { value in
print(value)
startSecond.send(())
}
let cancellable2 =
startSecond
.flatMap({ _ in
URLSession.shared.dataTaskPublisher(for: .init(string: "http://httpbin.org/delay/10")!)
// handle errors
})
.sink(receiveCompletion: { completion in
print(completion)
}, receiveValue: { value in
print(value)
})
startFirst.send(()) // start first network request
https://stackoverflow.com/questions/70078154
复制相似问题