I’m utilizing Commentary and @Observable all through my app, and usually I do not actually have a necessity for Mix. Nonetheless, I’ve run into conditions the place I would like debouncers and throttlers and I do not see different simple resolution besides to do it previous method… So, thus the query, trigger I do not know what’s a correct method to do that when utilizing Commentary framework.
I did it previous method:
remaining class Debouncer: ObservableObject {
personal var cancellables = Set()
personal let tapSubject = PassthroughSubject()
func sendTap(for itemId: String?) {
guard let itemId else { return }
tapSubject.ship(itemId)
}
var handleFavoriteTap: ((String) -> Void)?
init() {
tapSubject
.debounce(for: .milliseconds(300), scheduler: RunLoop.principal)
.sink { [weak self] itemId in
self?.handleFavoriteTap?(itemId)
}
.retailer(in: &cancellables)
}
}
then:
@State personal var debouncer = Debouncer()
and:
.onAppear {
debouncer.handleFavoriteTap = { itemId in
firestoreManager.addFavorite(documentID: itemId)
}
and eventually:
.onTapGesture {
debouncer.sendTap(for: merchandise.id)
}
So it really works… Additionally, I kinda did it with AsyncStream (it appears to be working accurately):
@State personal var tapContinuation: AsyncStream.Continuation?
personal func startTapStream() {
let tapStream = AsyncStream { continuation in
self.tapContinuation = continuation
}
Activity {
for await itemId in tapStream
.debounce(for: .milliseconds(200))
{
firestoreManager.addFavoriteTip(documentID: itemId)
}
}
}
and:
.onAppear {
startTapStream()
}
However I’m not likely certain which method to take, or if there’s a greater strategy to deal with this as a result of there are in all probability extra issues I ought to contemplate in AsyncStream code (e.g., holding a reference to present faucet job so I can cancel it on onDisappear…). It simply appears like an excessive amount of trouble for a easy debounce, and importing Mix only for it additionally does not sound nice…So what’s a most popular method as of late for this?