Created
March 3, 2021 07:38
-
-
Save mahdit83/2fc853dc12fa81202de7b6e66eab51f2 to your computer and use it in GitHub Desktop.
Consumable live data
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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.