Created
February 12, 2019 15:45
-
-
Save wellingtoncosta/794e4832006857b65bb3f8392b46e843 to your computer and use it in GitHub Desktop.
This file contains 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 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