Skip to content

Instantly share code, notes, and snippets.

@lgastler
Created January 28, 2023 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgastler/7906ba97f5b929ffe9043059beb03f06 to your computer and use it in GitHub Desktop.
Save lgastler/7906ba97f5b929ffe9043059beb03f06 to your computer and use it in GitHub Desktop.
DebouncedObservedObject
import Combine
import Foundation
@propertyWrapper @dynamicMemberLookup
class DebouncedObservedObject<Wrapped: ObservableObject>: ObservableObject {
var wrappedValue: Wrapped
private var subscription: AnyCancellable?
init(wrappedValue: Wrapped, delay: Double = 1) {
self.wrappedValue = wrappedValue
subscription = wrappedValue.objectWillChange.debounce(for: .seconds(delay), scheduler: DispatchQueue.main)
.sink { [weak self] _ in
self?.objectWillChange.send()
}
}
subscript<Value>(dynamicMember keyPath: ReferenceWritableKeyPath<Wrapped, Value>) -> Value {
get { wrappedValue[keyPath: keyPath] }
set { wrappedValue[keyPath: keyPath] = newValue }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment