Anyone here handling loading state by just setting...
# android
f
Anyone here handling loading state by just setting
loading = true
at the beginning of a coroutine and
loading = false
at the end? (loading is LiveData) If yes, how do you make sure that the loading value is set to false even if the coroutine was canceled? Should I wrap
loading = false
with
withContext(NonCancellable)
?
Edit: Okay this only works in finally blocks.
j
I think you should change this approach and emit state using, for example, a sealed class
f
alright, thank you
Do you use this sealed class when you return LiveData?
I was hearing some negative opinions about that but it seems the only working solution
j
what negative opinions?
f
well someone was criticizing that the error state is kept in the LiveData value, although it should be a single time event
but the data in the Success case is not a single time event
j
it depends of the error, if the error is a normal screen and not a snackbar, you don’t need the second livedata
and with an snackbar you can have only one livedata too, you can change the state with the snackbar onDismiss callback so when you rotate the screen, the snackbar should not appear
f
what do you mean by "second liveata"?
a
curious, did you encounter this in a real case? it shouldn’t get canceled if you are in view model scope since it has longer lifecycle than the view
for cancelable scenarios you probably should be using async instead of launch, then use try finally to ensure cancellation
f
no I didn't encounter this myself
but I think it would be problematic if the LiveData was in a larger scoped ViewModel
j
second livedata = your singleLiveEvent to emit error states -> show error snackbars one time
f
ah I get it, thank you
👍 1
a
Copy code
viewModel.state.observe(this) {
    it?.let { state ->
        when(state){
            is Loading -> { // show progressBar }
            is Success -> { // set data }
            is Error -> {
                        // show error via snackbar or toast
                        viewModel.onErrorMsgShown()
                    }
        }
    }
}
fun onErrorMsgShown() {
    state.value = null
}
I use the above approach to show error msgs once but i m not sure if this is good
the method at the end is in viewmodel
f
very interesting, thank you!