Skip to content

Instantly share code, notes, and snippets.

@CompileConnected
Last active September 22, 2021 09:40
Show Gist options
  • Select an option

  • Save CompileConnected/046cfefd0a99a036cbe4f82d04ea7484 to your computer and use it in GitHub Desktop.

Select an option

Save CompileConnected/046cfefd0a99a036cbe4f82d04ea7484 to your computer and use it in GitHub Desktop.
SingleLiveEvent.kt
class SingleLiveEvent<T> : MutableLiveData<T> {
constructor(value: T) : super(value)
constructor() : super()
private val mPending = AtomicBoolean(false)
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
if (hasActiveObservers()) {
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
}
// Observe the internal MutableLiveData
super.observe(owner, { t ->
if (mPending.compareAndSet(true, false)) {
observer.onChanged(t)
}
})
}
@MainThread
override fun setValue(@Nullable t: T?) {
mPending.set(true)
super.setValue(t)
}
/**
* Used for cases where T is Void, to make calls cleaner.
*/
@MainThread
fun call() {
value = null
}
companion object {
private const val TAG = "SingleLiveEvent"
}
}
fun <T> MutableLiveData<Resource<T>>.set(state: State, data: T? = null, message: String? = null) =
postValue(Resource(state, data, message))
fun <T> MutableLiveData<Resource<T>>.setSuccess(data: T?) =
set(State.SUCCESS, data)
fun <T> MutableLiveData<Resource<T>>.setLoading() =
set(State.LOADING, value?.data)
fun <T> MutableLiveData<Resource<T>>.setError(message: String? = null) =
set(State.ERROR, value?.data, message)
fun <T> MutableLiveData<Resource<T>>.setError(message: String? = null, data: T?) =
set(State.ERROR, data, message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment