【问题标题】:iOS Combine debounce fire manuallyiOS 手动组合去抖动
【发布时间】:2021-11-10 08:25:04
【问题描述】:
我正在使用 iOS 组合框架的 debounce 运算符。
var subject = PassthroughSubject<Void, Never>()
var cancellable: Cancellable!
cancellable = subject
.debounce(for: .seconds(0.1), scheduler: RunLoop.main)
.sink {
// doSomething
}
现在我想在计时器(0.1 秒)结束之前“触发事件”来做一些事情。
有没有可以调用它的方法?
【问题讨论】:
标签:
ios
swift
combine
debouncing
【解决方案1】:
最简单的方法是使用handleEvents 方法通过管道管理任何事件。虽然不是唯一一个而且更酷。
您可以使用两个订阅来分隔您的逻辑。除了您不想延迟的第一种情况,您可以只使用first() 或prefix(1) 取第一个值。
我和你分享一个例子:
import Foundation
import Combine
let subject = PassthroughSubject<Void, Never>()
// The shared one is optional, depending on the case.
For heavy publishers which for example do network requests is a good practice.
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)
request unlimited
receive value: (())
Normal
receive value: (())
receive value: (())
Debounced