Skip to content

Instantly share code, notes, and snippets.

@YuanLiou
Last active February 1, 2021 15:53
Show Gist options
  • Save YuanLiou/6fd642d5cbf3ce1770eb565fefdab470 to your computer and use it in GitHub Desktop.
Save YuanLiou/6fd642d5cbf3ce1770eb565fefdab470 to your computer and use it in GitHub Desktop.
SingleLiveData Sample #Kotlin #sample #LiveData
public class SingleLiveData<T> : MutableLiveData<T> {
private val pending = AtomicBoolean(false)
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<T>) {
super.observe(owner, object : Observer<T>() {
override fun onChanged(t: T?) {
// compareAndSet(expect, update)
// here if `true` then set to false
if (pending.compareAndSet(true, false)) {
observe.onChanged(t)
}
}
})
}
@MainThread
override fun setValue(t: T?) {
pending.set(true)
super.setValue(t)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment