Created
February 4, 2026 12:37
-
-
Save aroranubhav/68a9c606f9997716fdbdb96d4f646e49 to your computer and use it in GitHub Desktop.
LiveData Implementation without Lifecycle
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
| typealias CustomObserver<T> = (T?) -> Unit | |
| /** | |
| * A simple data holder class that allows observing changes to the data without being tied to an Android Lifecycle. | |
| * This is useful in scenarios where you need LiveData-like behavior in non-UI components or when you want to | |
| * manually manage the observer lifecycle. | |
| * | |
| * @param T The type of data held by this instance. | |
| */ | |
| class LiveDataWithoutLifecycle<T> { | |
| private var data: T? = null | |
| private val observers = arrayListOf<CustomObserver<T>>() | |
| /** | |
| * Sets the value of the data and notifies all registered observers. | |
| * | |
| * @param value The new value to be set. | |
| */ | |
| fun setValue(value: T) { | |
| this.data = value | |
| observers.forEach { observer -> | |
| observer(this.data) | |
| } | |
| } | |
| /** | |
| * Returns the current value of the data. | |
| * | |
| * @return The current value, or null if no value has been set. | |
| */ | |
| fun getValue(): T? { | |
| return this.data | |
| } | |
| /** | |
| * Adds an observer to be notified when the data changes. | |
| * Note: Since this class is not lifecycle-aware, you must manually call [removeObserver] | |
| * to prevent memory leaks. | |
| * | |
| * @param observer The callback to be invoked when the data changes. | |
| */ | |
| fun observe(observer: CustomObserver<T>) { | |
| observers.add(observer) | |
| } | |
| /** | |
| * Removes a previously added observer. | |
| * | |
| * @param observer The observer to be removed. | |
| */ | |
| fun removeObserver(observer: CustomObserver<T>) { | |
| observers.remove(observer) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment