Last active
May 7, 2019 10:38
-
-
Save rodolfoizidoro/6ec8e8ea3f0af3e9580e31fe1ff16039 to your computer and use it in GitHub Desktop.
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
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.LiveData | |
interface StateLiveData<R, E> { | |
fun observe(owner: LifecycleOwner, onSuccess: (R) -> Unit, onError: (E) -> Unit = {}, onLoading: (Boolean) -> Unit = {}) | |
val loadingLiveData: LiveData<Boolean> | |
val successLiveData: LiveData<R> | |
val errorLiveData: LiveData<E> | |
} |
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
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.MutableLiveData | |
import androidx.lifecycle.Observer | |
class StateMutableLiveData<R, E> : StateLiveData<R, E> { | |
val success = MutableLiveData<R>() | |
val loading = MutableLiveData<Boolean>() | |
val error = MutableLiveData<E>() | |
override val loadingLiveData: LiveData<Boolean> get() = loading | |
override val successLiveData: LiveData<R> get() = success | |
override val errorLiveData: LiveData<E> get() = error | |
override fun observe(owner: LifecycleOwner, onSuccess: (R) -> Unit, onError: (E) -> Unit, onLoading: (Boolean) -> Unit) { | |
successLiveData.observe(owner, Observer { | |
onSuccess.invoke(it) | |
}) | |
loadingLiveData.observe(owner, Observer { | |
onLoading.invoke(it) | |
}) | |
errorLiveData.observe(owner, Observer { | |
onError.invoke(it) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment