Last active
October 21, 2018 08:38
-
-
Save niwatly/cc875ce7189e097cf00463b047dbc37f to your computer and use it in GitHub Desktop.
Convenient LiveData for observing click event.
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
| /** | |
| * LiveData that ignore current value broadcast when observe. | |
| * Like PulseLiveData(https://gist.github.com/niwatly/3b1ee17f25a63276e36194cd86f9b223), but ActionLiveData holds last value. so, result is defferent when getValue. | |
| * | |
| * 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 | |
| * | |
| * see also: | |
| * https://qiita.com/KazaKago/items/acce0c1a970441b44f39 | |
| */ | |
| class ActionLiveData<T>: MediatorLiveData<T>() { | |
| private val pending: AtomicBoolean = AtomicBoolean(false) | |
| @MainThread | |
| fun observeSingle(owner: LifecycleOwner, callback: ((data: T) -> Unit)) { | |
| removeObservers(owner) | |
| // Observe the internal MutableLiveData | |
| super.observe(owner, Observer { | |
| if (pending.compareAndSet(true, false)) { | |
| it?.let { | |
| callback(it) | |
| } | |
| } | |
| }) | |
| } | |
| override fun observe(owner: LifecycleOwner, observer: Observer<T>) { | |
| TODO("not implemented") | |
| } | |
| @MainThread | |
| 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