Created
December 27, 2019 01:18
-
-
Save marcuswestin/e9a4eaceca15bb61b89b1c35c5158730 to your computer and use it in GitHub Desktop.
SwiftUI Combine ObservableProperty
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 | |
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