Skip to content

Instantly share code, notes, and snippets.

@rodolfoizidoro
Last active May 8, 2019 14:19
Show Gist options
  • Save rodolfoizidoro/462f69852c124974189bfb3c6859d455 to your computer and use it in GitHub Desktop.
Save rodolfoizidoro/462f69852c124974189bfb3c6859d455 to your computer and use it in GitHub Desktop.
//Abstração
class TestLiveData<T, Q> : TestLiveDataI<T, Q> {
val success = MutableLiveData<T>()
val loading = MutableLiveData<Boolean>()
val error = Event<Q>()
override fun successLiveData(): LiveData<T> = success
override fun loadingLiveData(): LiveData<Boolean> = loading
override fun errorLiveData(): LiveData<Q> = error
override fun observe(
owner: LifecycleOwner,
onSuccess: (T) -> Unit,
onFail: (Q) -> Unit,
onLoading: (Boolean) -> Unit
) {
successLiveData().observe(owner, Observer {
onSuccess.invoke(it)
})
loadingLiveData().observe(owner, Observer {
onLoading.invoke(it)
})
errorLiveData().observe(owner, Observer {
onFail.invoke(it)
})
}
}
interface TestLiveDataI<T, Q> {
fun observe(owner: LifecycleOwner, onSuccess: (T) -> Unit = {}, onFail: (Q) -> Unit = {}, onLoading: (Boolean) -> Unit= {} )
fun successLiveData(): LiveData<T>
fun loadingLiveData(): LiveData<Boolean>
fun errorLiveData(): LiveData<Q>
}
//ViewModel
private val teste = TestLiveData<List<Movie>, String>()
fun teste(): TestLiveDataI<List<Movie>, String> = teste
{
teste.success.value = movies.sortedByDescending { it.releaseDate }
} catch (t: Throwable) {
teste.error.value = t.message
}
//Activity
viewModel.teste().observe(this, onSuccess = { list ->
rvMovies.adapter = MoviesAdapter(list) {
flowController.openMovieDetail(it)
}
}, onFail = {
toast(it)
}, onLoading = {
Log.d("Show progrees: ", it.toString())
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment