[英]Add delay to publisher based on value with Combine Framework in iOS
我有一個發布者public let motionSubject = PassthroughSubject<Bool, Never>()
我正在傾聽價值觀
motionManager.motionSubject.sink(receiveValue: { [weak self] isMoving in
self?.isMoving = isMoving
}).store(in: &subscription)
如果發布的值為“true”,我想添加 2 秒延遲,因為我想給出 2 秒的聲音反饋。
我嘗試在 motionSubject.send(true) 之前添加 DispatchQueue.asynafter 但它沒有用。
有誰知道我怎么能做到這一點?
謝謝。
您可以使用.throttle 或.debounce,我認為在您的情況下,throttle 會更有益,因為它不會在接收到值后暫停。 因此,如果您想專門針對真實價值進行操作,則需要執行以下操作:
motionManager.motionSubject
.filter { $0 == true } // will only emit through values which answer this query
.throttle(for: .milliseconds(2000), scheduler: DispatchQueue.main, latest: true) // will publish the latest value after 2 seconds delay since the first pulishment
.sink(receiveValue: { [weak self] isMoving in
self?.isMoving = isMoving
}).store(in: &subscription)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.