Home > Blockchain >  When to use derivedStateOf in Jetpack Compose?
When to use derivedStateOf in Jetpack Compose?

Time:03-26

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://developer.android.com/courses/pathways/compose#codelab-https://developer.android.com/codelabs/jetpack-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

CodePudding user response:

Yes, topicsResponse is Result.Error will be calculated on each recomposition, but if the result does not change - you shouldn't care about that at all. Practically, this "calculation" have no impact on performance.

You could use remember here and it would work, but remember itself has much bigger cost than is operation. So you would loose performance in that regard.

As to derivedStateOf - there is no point using it here. It is used to track multiple state changes

  • Related