Skip to content

Instantly share code, notes, and snippets.

@niwatly
Last active October 21, 2018 08:23
Show Gist options
  • Save niwatly/3b1ee17f25a63276e36194cd86f9b223 to your computer and use it in GitHub Desktop.
Save niwatly/3b1ee17f25a63276e36194cd86f9b223 to your computer and use it in GitHub Desktop.
pseudo-stateless LiveData
/**
* LiveData that behaviors like as stateless. the set value will be override by null.
* Obervers have soem limit not to detect null-value-to-override as new value.
*
* cited:
* https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java
* https://android.jlelse.eu/android-arch-handling-clicks-and-single-actions-in-your-view-model-with-livedata-ab93d54bc9dc
*/
class VoidPulseLiveData : MediatorLiveData<Unit>() {
fun <T> addDetector(source: LiveData<T>, detector: (value: T?) -> Boolean) {
addSource(source) {
if (detector(it)) {
beat()
}
}
}
@MainThread
fun observeOnce(owner: LifecycleOwner, callback: () -> Unit) {
super.observe(owner, object: Observer<Unit> {
override fun onChanged(t: Unit?) {
if (t != null) {
removeObserver(this)
callback()
if (hasObservers().not()) {
value = null
}
}
}
})
}
@MainThread
fun observeSingle(owner: LifecycleOwner, callback: () -> Unit) {
removeObservers(owner)
super.observe(owner, Observer {
if (it != null) {
callback()
value = null
}
})
}
override fun observe(owner: LifecycleOwner, observer: Observer<Unit>) {
TODO("not implemented")
}
@MainThread
fun beat() {
postValue(Unit)
}
}
class PulseLiveData<T> : MutableLiveData<T>() {
@MainThread
fun observeOnce(owner: LifecycleOwner, callback: (data: T) -> Unit) {
super.observe(owner, object: Observer<T> {
override fun onChanged(t: T?) {
t?.let {
removeObserver(this)
callback(it)
if (hasObservers().not()) {
value = null
}
}
}
})
}
@MainThread
fun observeSingle(owner: LifecycleOwner, callback: (data: T) -> Unit) {
removeObservers(owner)
super.observe(owner, Observer {
if (it != null) {
callback(it)
value = null
}
})
}
override fun observe(owner: LifecycleOwner, observer: Observer<T>) {
TODO("not implemented")
}
@MainThread
fun beat(v: T) {
postValue(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment