Last active
September 22, 2021 09:40
-
-
Save CompileConnected/046cfefd0a99a036cbe4f82d04ea7484 to your computer and use it in GitHub Desktop.
SingleLiveEvent.kt
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
| 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" | |
| } | |
| } |
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
| 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