https://kotlinlang.org logo
#compose
Title
# compose
f

Fanilog

05/19/2022, 9:30 AM
Hello trying to dig a bit more in compose and I’m not really sure. Despite having the remember returning me the job, is there another difference ?
Copy code
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(key1 = lifecycleOwner) {
    launch {
and
Copy code
val lifecycleOwner = LocalLifecycleOwner.current
remember(key1 = lifecycleOwner) {
    with(lifecycleOwner) {
        lifecycleScope.launch {
?
f

Filip Wiesner

05/19/2022, 9:40 AM
I am not really sure but I think that the
LocalLifecycleOwner
contains lifecycle of your activity or fragment so if you launch coroutine from it, it won't be scoped to your composable. You should use either
Copy code
LaunchedEffect(key) { 
  mySuspendFunction()
}
or
Copy code
val scope = rememberCoroutineScope()
...
// not in root composable, e.g onClick lambda
scope.launch {
  mySuspendFunction()
}
I am not sure why are you using
lifecycleOwner
in a first place.
f

Fanilog

05/19/2022, 9:42 AM
Yes in fact with more context it could be better. I’m have a flow sending navigation event, and I’m trying to listen it inside the MainActivity and in the
collect
I’m dispatching the event
So I’m trying to avoid to have something scope to a composable
f

Filip Wiesner

05/19/2022, 9:44 AM
So you are listening to a navigation event in your UI code but you don't want it to be tied to a lifecycle of your UI?
f

Fanilog

05/19/2022, 9:45 AM
Yes, I don’t want to be tied to a particular composable, but more to the global lifecycle of the app
but maybe it’s a good way to process
f

Filip Wiesner

05/19/2022, 9:49 AM
Then consider moving it from your composable 😄 Sorry, I can't help you without more context. But it seems to me that what you are doing is not really a good idea. You should be collecting your flow only when your composable is visible/in composition. I don't see a valid case of starting a collection when composable enters composition and not stopping when it exits.
Not mentioning the case when composable exits and enters composition multiple times resulting to multiple collectors being launched
f

Fanilog

05/19/2022, 9:50 AM
Ok you are right. I might consider to use it with a LaunchEffect or doing it somewhere else
f

Filip Wiesner

05/19/2022, 9:52 AM
Maybe I just don't understand your use case but from quick look it does not look good. Good luck 🤞
6 Views