Skip to content

Instantly share code, notes, and snippets.

@Wottrich
Created January 7, 2022 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wottrich/61a251e5e0464c59247cc9e0e7494ab4 to your computer and use it in GitHub Desktop.
Save Wottrich/61a251e5e0464c59247cc9e0e7494ab4 to your computer and use it in GitHub Desktop.
SingleLiveEvent example
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