I'm confused by why I can't save the CoroutineScop...
# compose
d
I'm confused by why I can't save the CoroutineScope of a LaunchedEffect into a variable and then use it in a callback.
Copy code
LaunchedEffect(mapbox) {
            val scope = this
            val map = mapbox.awaitMap();

            map.addOnCameraIdleListener {
                Timber.i("This is called")
                scope.launch {
                    Timber.i("This is never called")
                    repo.setMapPosition(map.cameraPosition)
                }
            }

            Timber.i("This is also called")
        }
z
In your code I think it’s because your coroutine scope immediately ends (since the lambda returns), so newly launched coroutines will never actually start and just end immediately. For this sort of pattern, you’re probably better off using coroutines APIs to either create a Flow from your callback (if it gets called multiple times), or wrap it in a suspend function that suspends the coroutine until the callback is invoked (if it’s only called once).
1
If you really do need a coroutine scope to invoke in callbacks from other compose code, you can use
rememberCoroutineScope
, but I don’t think that’s the right tool here.
d
Thanks! I think this is a general kotlin misunderstanding then
👍🏻 1