Side Effects: RememberCoroutineScope - devrath/ComposeAlchemy GitHub Wiki

  • We use remember co-routine scope when we want to launch a coroutine outside the composable but scoped to the lifecycle of the composable

Practical Demo Sample-1

  • Lets consider the below example where we display
  • The coroutineScope is bound to this composable - If the composable is not part of the UI hierarchy, Then the scope is canceled.
  • Say if we continuously click the button, All the co-routines are launched in a queue one by one starting from the first till the last one is displayed.
@Composable
fun LaunchedEffectDemo2Screen(modifier: Modifier = Modifier) {

    var counterState by remember { mutableIntStateOf(0) }

    val snackbarHostState = remember {
        SnackbarHostState()
    }
    
    val coroutineScope = rememberCoroutineScope()

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        snackbarHost = {
            SnackbarHost(
                hostState = snackbarHostState
            )
        }
    ) { padding ->
        Box(
            modifier = Modifier.fillMaxSize().padding(padding),
            contentAlignment = Alignment.Center
        ) {
            Button(
                onClick = {
                    counterState++

                    if(counterState % 2 == 0){
                        coroutineScope.launch {
                            snackbarHostState.showSnackbar(" $counterState --> It is a even number")
                        }
                    }
                }
            ) {
                Text(text = "Current Value -> $counterState")
            }
        }
    }

}

Practical Demo Sample-1

@Composable
fun TypeRememberCoroutineScope(navController: NavHostController) {

    val custScope = rememberCoroutineScope()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(10.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Button(
                onClick = {
                    custScope.launch {
                        delay(3000L)
                        println("Hello World!")
                    }
                }) {
                Text(
                    text = "Click here",
                    color = Color.White,
                    textAlign = TextAlign.Center
                )
            }
        }

    }

}