Last active
June 18, 2019 06:54
-
-
Save vitoksmile/894468fd7e9eefa3987de9e305b81105 to your computer and use it in GitHub Desktop.
LiveData to hold not observed values to notify UI about these values after appearance of active observers
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
/** | |
* Hold not observed values to notify UI about these values after appearance of active observers | |
*/ | |
class BufferedLiveData<T> : LiveData<T>() { | |
/** | |
* Object to synchronize adding values to buffer in #postValue | |
*/ | |
private val lock = Any() | |
/** | |
* Not observed values | |
*/ | |
private val buffer = LinkedList<T>() | |
override fun setValue(value: T) { | |
if (hasActiveObservers()) { | |
super.setValue(value) | |
} else { | |
// Add the value to buffer | |
buffer.add(value) | |
} | |
} | |
override fun postValue(value: T) { | |
if (hasActiveObservers()) { | |
super.postValue(value) | |
} else { | |
// Add the value to buffer with synchronization | |
synchronized(lock) { | |
buffer.add(value) | |
} | |
} | |
} | |
override fun onActive() { | |
val iterator = buffer.iterator() | |
// Check if buffer isn't empty and the LiveData has active observers | |
while (iterator.hasNext() && hasActiveObservers()) { | |
val value = iterator.next() | |
// Notify observers about the value | |
setValue(value) | |
// Remove the observed value from buffer | |
iterator.remove() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment