Skip to content

Instantly share code, notes, and snippets.

@mahdit83
Created March 3, 2021 07:38
Show Gist options
  • Save mahdit83/2fc853dc12fa81202de7b6e66eab51f2 to your computer and use it in GitHub Desktop.
Save mahdit83/2fc853dc12fa81202de7b6e66eab51f2 to your computer and use it in GitHub Desktop.
Consumable live data
class ConsumableLiveData<T>(var consume: Boolean = false) : MutableLiveData<T>() {
private val pending = AtomicBoolean(false)
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, Observer<T> {
if(consume){
if(pending.compareAndSet(true,false)) observer.onChanged(it)
}else{
observer.onChanged(it)
}
})
}
override fun setValue(value: T) {
pending.set(true)
super.setValue(value)
}
}
@mahdit83
Copy link
Author

mahdit83 commented Mar 3, 2021

When a live data with some value, after view is retrieved, last value will trigger in view on observe method. If we wanna use some event live data like on some button click or some one time event, normal live data would not help. For achieving this we can use one time live data like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment