Skip to content

Instantly share code, notes, and snippets.

@wellingtoncosta
Created February 12, 2019 15:45
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 wellingtoncosta/794e4832006857b65bb3f8392b46e843 to your computer and use it in GitHub Desktop.
Save wellingtoncosta/794e4832006857b65bb3f8392b46e843 to your computer and use it in GitHub Desktop.
class ListUsersViewModel(
private val repository: UserRepository
) : CoroutineViewModel() {
private val users: MutableLiveData<List<User>> = MutableLiveData()
private val loading: MutableLiveData<Boolean> = MutableLiveData()
private val error: MutableLiveData<Throwable> = MutableLiveData()
fun users() = users as LiveData<List<User>>
fun loading() = loading as LiveData<Boolean>
fun error() = error as LiveData<Throwable>
fun getAll() {
jobs add launch {
loading.value = true
try {
users.value = repository.getAll().await()
loading.value = false
} catch(t: Throwable) {
users.value = emptyList()
error.value = t
} finally {
loading.value = false
}
}
}
fun getByUsername(username: String) {
jobs add launch {
loading.value = true
try {
val user = repository.getByUsername(username).await()
users.value = listOf(user)
} catch(t: Throwable) {
users.value = emptyList()
error.value = t
}
finally {
loading.value = false
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment