Introduction
viewModelScope.launch{} 대신 live data builder를 사용해보도록 합니다.
viewModelScope
init {
loadTopTwoDogsAsync()
}
private fun loadTopTwoDogsAsync() {
viewModelScope.launch {
logCoroutine("loadTopTwoDogsAsync", coroutineContext)
val list = runCatching { mainActivityRepository.getTopTwoDogsAsync() }
list.onSuccess {
_topDogsAsync.value = it.value
}.onFailure {
_snackbar.value = it.message.toString()
_snackbar.value = "loadTopTwoDogsAsync() " + it.message.toString()
}
}
}
viewModel.topDogsAsync.observe(this, Observer {
//Do Something
})
liveData
val liveDataResult = liveData {
emit(GeneralResult.Progress(true))
//This below function is a suspend function
val topTwoDogsResult = mainActivityRepository.getTopTwoDogsAsync()
emit(GeneralResult.SuccessGeneric(topTwoDogsResult.value))
}
viewModel.liveDataResult.observe(this, Observer {
when (it) {
is GeneralResult.Progress -> { }
is GeneralResult.SuccessGeneric<*> -> { }
is GeneralResult.Error -> { }
}
})
live data는 어떻게 동작할까요?
viewModelScope 대신에 써야만 할까요?
live data를 Emitting 하려면?
val liveDataResult = liveData {
logCoroutineThreadNameOnly("liveDataResult")
emit(GeneralResult.Progress(true))
emitSource(getTopTwoDogsLiveData())
}
private fun getTopTwoDogsLiveData(): LiveData<GeneralResult> = liveData {
while (true) {
delay(DELAY_BETWEEN_DOGS_IN_MS)
val topTwoDogsResult = mainActivityRepository.getTopTwoDogsAsync()
emit(topTwoDogsResult)
}
}