Last active
October 2, 2020 19:41
-
-
Save nerdsupremacist/b6218075fbb1b15e910f44a4c3d3b54f to your computer and use it in GitHub Desktop.
Debounced Property Wrapped
This file contains hidden or 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 SwiftUI | |
import Combine | |
@propertyWrapper | |
struct Debounced<Value>: DynamicProperty { | |
private class Box: ObservableObject { | |
let value = PassthroughSubject<Value, Never>() | |
@Published | |
private(set) var debounced: Value | |
private var store = Set<AnyCancellable>() | |
init<S : Scheduler>(wrappedValue: Value, for stride: S.SchedulerTimeType.Stride, scheduler: S) { | |
debounced = wrappedValue | |
value | |
.debounce(for: stride, scheduler: scheduler) | |
.sink { [unowned self] value in | |
self.debounced = value | |
} | |
.store(in: &store) | |
} | |
} | |
@ObservedObject | |
private var box: Box | |
var wrappedValue: Value { | |
get { | |
return box.debounced | |
} | |
nonmutating set { | |
box.value.send(newValue) | |
} | |
} | |
var projectedValue: Binding<Value> { | |
return Binding(get: { self.wrappedValue }, set: { self.wrappedValue = $0 }) | |
} | |
init<S : Scheduler>(wrappedValue: Value, for stride: S.SchedulerTimeType.Stride, scheduler: S) { | |
box = Box(wrappedValue: wrappedValue, for: stride, scheduler: scheduler) | |
} | |
init(wrappedValue: Value, for stride: TimeInterval) { | |
box = Box(wrappedValue: wrappedValue, for: .seconds(stride), scheduler: RunLoop.main) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment