Last active
February 1, 2021 15:53
-
-
Save YuanLiou/6fd642d5cbf3ce1770eb565fefdab470 to your computer and use it in GitHub Desktop.
SingleLiveData Sample #Kotlin #sample #LiveData
This file contains hidden or 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
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