我正在使用iOS Combine Framework的debounce Operator。
var subject = PassthroughSubject< Void, Never> ()
var cancellable: Cancellable!
cancellable = subject
.debounce(for: .seconds(0.1), scheduler: RunLoop.main)
.sink {
// doSomething。
}
現在我想在定時器(0.1秒)結束前 "觸發事件",讓doSomething。 是否有一個方法可以呼叫這個?
uj5u.com熱心網友回復:
在函式式方法中,你可以在處理樹的任何一級與你的值互動。在你的例子中,在debounce之前:
cancellable = subject
.handleEvents(
receiveOutput: { 輸出 in
//this is called on each new send.
//like subject.send(())。
},
receiveCompletion。{ 結果 in
//這是在發送完成時呼叫的。
//like subject.send(completion: .finished)
switch result {
case .finished:
print("ok")
case .failure(let error):
print("failure(error)")
}
}
)
.debounce(for: .seconds(0.1), scheduler: RunLoop.main)
.sink {
// doSomething。
}
uj5u.com熱心網友回復:
最簡單的方法是使用handleEvents方法來管理通過管道的任何事件。雖然不是唯一的方法,而且更酷。
你可以使用兩個訂閱來管理任何事件。
你可以使用兩個訂閱來分離你的邏輯。除了第一種情況,即你不想有延遲,你可以用first()或prefix(1)只取第一個值。
我和你分享一個例子:
import Foundation
import Combine
let subject = PassthroughSubject<Void, Never> ()
//共享的那個是可選的,取決于情況。
對于例如做網路請求的重型出版商是一個好的做法。
let sharedSubject = subject.share()
let normalCancellable = sharedSubject.first()
.sink { print("normal") }
let debouncedCancellable = sharedSubject
.debounce(for: .seconds(0.3), scheduler: RunLoop.main)
.sink { print("Debounced" ) }
subject.send()
subject.send()
subject.send()
輸出
receive subscription: (PassthroughSubject)
請求無限制
接收值: (())
Normal[/span
接收值: (()
接收值: (())
放棄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/306774.html
標籤:
下一篇:如何將計量單位作為單數名詞?
