Created
January 28, 2023 16:32
-
-
Save lgastler/7906ba97f5b929ffe9043059beb03f06 to your computer and use it in GitHub Desktop.
DebouncedObservedObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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