Skip to content

Instantly share code, notes, and snippets.

@vitoksmile
Last active June 18, 2019 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitoksmile/894468fd7e9eefa3987de9e305b81105 to your computer and use it in GitHub Desktop.
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
/**
* 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