Skip to content

Instantly share code, notes, and snippets.

@marcuswestin
Created December 27, 2019 01:18
Show Gist options
  • Save marcuswestin/e9a4eaceca15bb61b89b1c35c5158730 to your computer and use it in GitHub Desktop.
Save marcuswestin/e9a4eaceca15bb61b89b1c35c5158730 to your computer and use it in GitHub Desktop.
SwiftUI Combine ObservableProperty
import Combine
private var retainForever = [AnyCancellable]()
class ObservableProperty<T>: ObservableObject {
@Published private var value: T
init(initialValue: T) {
self.value = initialValue
}
func set(_ value: T) {
self.value = value
}
func get() -> T {
return self.value
}
typealias ValueHandler = (_ value: T) -> Void
typealias ChangeHandler = (_ newValue: T, _ previousValue: T) -> Void
func observe(_ handler: @escaping ValueHandler) {
let subscription = self.$value.sink(receiveValue: handler)
retainForever.append(subscription)
}
func onChange(_ handler: @escaping ChangeHandler) {
let subscription = self.$value.dropFirst().sink { (newValue) in
handler(newValue, self.value)
}
retainForever.append(subscription)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment