In my ViewModel I have
private val _topicsResponse = MutableStateFlow<Result<List<Topic>>>(Result.Initial)
val topicsResponse = _topicsResponse.asStateFlow()
I fetch data (topics) from the server and that's why the data is wrapped in Result<T> class. It can be Result.Initial, Result.Loading, Result.Success and Result.Error
In my compose function of topics screen I have the logic for displaying the error using Snackback
val topicsResponse: Result<List<Topic>> by topicsViewModel.topicsResponse.collectAsState()
Box(modifier = Modifier.fillMaxSize()) {
...
if (topicsResponse is Result.Error) {
Snackbar(
action = {
Button(onClick = { topicsViewModel.loadTopics() }) {
Text(stringResource(id = R.string.retry_text))
}
},
modifier = Modifier
.padding(8.dp)
.align(Alignment.BottomCenter)
) { Text(text = "Test error message") }
}
}
Is it good to use topicsResponse is Result.Error here?
Because I was reading about derivedStateOf at https://developer.android.com/codelabs/jetpack-compose-advanced-state-side-effects?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fcompose%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fjetpack-compose-advanced-state-side-effects#8
So I'm not sure if I should use
val showSnackBarError by remember {
derivedStateOf {
topicsResponse is Result.Error
}
}
or just val showSnackBarError = topicsResponse is Result.Error
topicsViewModel.topicsResponse.collectAsState() - collectAsState already has remember inside its implementation
but still topicsResponse is Result.Error is going to be calculated on each recomposition even if the result of this condition is going to be the same as I understand