eric-ampire / android-mvi-architecture

23 stars 7 forks source link

Crash without internet connection #2

Closed Barros9 closed 4 years ago

Barros9 commented 4 years ago

First, good example and good article on medium. If I turn off internet connection the app crash, could be it's trying to get "userApi.getUser()" on main thread? I moved userApi.getUser() in a variable and I pass it to the updateState and now it works. What do you think? I'm trying to understand the behavior with coroutines.

private fun fetchData() {
    viewModelScope.launch(Dispatchers.IO) {
        try {
            updateState { it.copy(isLoading = true) }
            val userList = userApi.getUser()
            updateState { it.copy(isLoading = false, users = userList) }
        }
        catch (e: Exception) {
            updateState { it.copy(isLoading = false, errorMessage = e.message) }
        }
    }
}
eric-ampire commented 4 years ago

You can fix this issue by updating updateState methods like this https://github.com/eric-ampire/android-mvi-architecture/commit/eccd908aa438ef081fc35b75892f2247eafa8e4b

private suspend fun updateState(handler: suspend (intent: UserState) -> UserState) {
    _state.postValue(handler(state.value!!))
}
eric-ampire commented 4 years ago

https://github.com/eric-ampire/android-mvi-architecture/commit/eccd908aa438ef081fc35b75892f2247eafa8e4b

Barros9 commented 4 years ago

Great, thank you!