Created
January 7, 2022 20:39
-
-
Save Wottrich/61a251e5e0464c59247cc9e0e7494ab4 to your computer and use it in GitHub Desktop.
SingleLiveEvent example
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
import androidx.annotation.MainThread | |
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.MutableLiveData | |
import androidx.lifecycle.Observer | |
import java.util.concurrent.atomic.AtomicBoolean | |
class SingleLiveEvent<T> : MutableLiveData<T> { | |
constructor() : super() | |
constructor(initialValue: T) : super(initialValue) | |
private val pending = AtomicBoolean(false) | |
@MainThread | |
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { | |
super.observe(owner, { t -> | |
if (pending.compareAndSet(true, false)) { | |
observer.onChanged(t) | |
} | |
}) | |
} | |
@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