Home > Software design >  Jetpack Compose: When does a Coroutine-Scope leave the Composition?
Jetpack Compose: When does a Coroutine-Scope leave the Composition?

Time:01-10

From the official documentation: "rememberCoroutineScope is a composable function that returns a CoroutineScope bound to the point of the Composition where it's called. The scope will be cancelled when the call leaves the Composition."

Please see here for the full text: Documentation

What is meant by "leaving the Composition"?

Can someone provide a concrete example? Currently can't imagine how the bold sentence is meant.

CodePudding user response:

Assume that there is a button in your UI, on clicking the button you are doing some background task using coroutine. So the code looks like

@Composable
fun ButtonComposable() {
    val scope = rememberCoroutineScope()
    Button(onClick = {
        scope.launch {
            // Background task
        }
    })
}

In the above code, the rememberCoroutineScope() function creates a CoroutineScope that is tied to the lifetime of the composition (ButtonComposable), or in simple terms the CoroutineScope scope will be active till ButtonComposable is used in the UI or till ButtonComposable does not change.

To explain further, CoroutineScope (scope) created by rememberCoroutineScope() function can be killed/cancelled by the below cases

  • If the Button (ButtonComposable) is removed from the UI.
  • If the input value of the button changes - In this case the button is not removed from the UI, but if the button`s value changes like text,color or any other factor the composition needs to be rebuilt, which kills the CoroutineScope (scope)
  • Related