How to manage error reporting as a side effect in Jetpack Compose

Viewed 402

I'm playing around with Jetpack Compose and I think I have a side effect in my composable, which tries to send an error report when it finds an unexpected value.

For example:

@Composable
fun SampleComposable(state: State, text: String) {
    when (state) {
        value1 -> {
            // show composable
        }
        value2 -> {
            // show composable
        }
        else -> {
            // send an error report
        }
    }
    Text(text)
}

So I believe whenever state or text changes, this will recompose. If state is an unexpected value, and text changes, it will send another error report. So I think there's a side effect in the else block.

Is there a way I should be structuring this code so that an error report isn't sent every time?

1 Answers

In this case you can use LaunchedEffect:

when (state) {
    value1 -> {
        // show composable
    }
    value2 -> {
        // show composable
    }
    else -> {
        LaunchedEffect(state) {
            // send an error report
        }
    }
}

LaunchedEffect lambda will only be executed once when added to the compose view tree, including removing and reattaching in case your state takes a valid value and then reverting to a non-valid one.

Also, by specifying state as a key, you can re-run it if two different invalid states appear in sequence.

Note that this lambda is run on a coroutine scope, so you can call suspend functions, but the scope will be cancelled once LaunchedEffect is removed from the view tree.

Check out more about side effects in Thinking in Compose and side effects documentation

Related