What could be a clean approach to validate is a co...
# compose
m
What could be a clean approach to validate is a composable function is "active" / in the composition stack? I.E We use circuit so we have our
present
composable function. There we lunch a coroutine to execute some logic. The coroutine uses an application scope as we want the execution to continue even if the user leaves the screen, but when we get the result we don't want to pop if we are not "on that screen"
z
Assuming by “pop” you’re referring to a navigation action, then you could do a few things(typing on phone so might abbreviate). You could use a state:
Copy code
var active by remember { mutableStateOf(true) }
DisposableEffect {
  appScope.launch {
    doThing()
    if (active) pop()
  }
  onDispose { active = false }
}
Or do it just with coroutines:
Copy code
LaunchedEffect {
  val job = appScope.launch {
    doThing()
  }
  job.join()
  pop()
}
thank you color 1
m
Ha sorry yeah pop means a navigation event. We added
Copy code
var isPresenting by remember { mutableStateOf(true) }

        // Track lifecycle of present function
        LaunchedEffect(Unit) {
            isPresenting = true
        }

        // When composable gets removed, deactivate it
        DisposableEffect(Unit) {
            onDispose {
                isPresenting = false
            }
        }
and
Copy code
onSuccess = {
                                    if (isPresenting) {
                                        navigator.pop()
                                    }
                                },
which seems to be a similar approach?
It just looked a bit hacky to us initial but looks like a viable option
z
You don’t need to launch a coroutine to re-initialize the state to true, it’s already initialized to true so that’s a noop
Well it’s always gonna be a bit hacky to work around structured concurrency, that’s by design to discourage it 😛
m
Gotcha! And dffo right on the init bit. Thanks!
Altho, I im not sure a pattern of actions living longer than the screen is something that uncommon?
z
No but I think there’s better ways to structure it. Eg have some higher-level presenter or service object with function that your composable calls so the long-lived task is closer to the scope that owns it, and hides the actual scope of the request from the caller. Then your composable could just do
Copy code
LaunchedEffect {
  appService.doThing()
  pop()
}
and not worry about all the lifecycle management stuff that’s really not its concern. Keeping the violation of SC in a separate function also makes it a lot easier to test, which is extra important in these cases.
1
m
Ah I see.. yeah I think you are right here. Will deffo take a look at how we could structure it better, Thanks for the feedback!