Created
August 11, 2022 22:15
-
-
Save outrowender/790af1efedf71efd8e7b474a8f1974d8 to your computer and use it in GitHub Desktop.
A observable to a single listener in Swift
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
// | |
// Observable.swift | |
// Created by Wender on 11/08/22. | |
// | |
class Observable<T> { | |
private(set) var value: T { | |
didSet { | |
listener?(value) | |
} | |
} | |
/// The listener registered to this event | |
/// TODO: Maybe allow multiple listeners? | |
private var listener: ((T) -> Void)? | |
/// Initialize you observable to later get values on it | |
init(_ value: T) { | |
self.value = value | |
} | |
/// You can subscribe to get new values for this object | |
func subscribe(_ listener: @escaping(T) -> Void) { | |
listener(value) | |
self.listener = listener | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment