Hi ! I have a `@Composable` : `GamePage` , which i...
# compose
l
Hi ! I have a
@Composable
:
GamePage
, which is using a native library. But this native library must be stopped when not needed any more:
Copy code
@Composable
fun GamePage() {
val myLib = MyLib()

...
myLib.stop()
}
So, is there a way to ? 1. Build a new MyLib instance at each recomposition 2. But also stop it before the next recomposition 3. Can I wait some milliseconds before "commiting" the next recomposition ?
k
Sounds like you're looking for
DisposableEffect
👍🏾 1
👍 1
l
Thank you. I've looked at DisposableEffect documentation, but I did not thought that it was adapted for my use case 🙂
k
It's a bit vague right now, but it sounds like you'd
remember
your
MyLib
with one of the existing wrappers, and then call
stop()
on it in
DisposableEffect
of this composable
👍 1
👍🏾 1
l
By wrappers, do you mean
remember
or
rememberSaveable
?
l
Copy code
@Composable
fun HomeScreen(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    onStart: () -> Unit, // Send the 'started' analytics event
    onStop: () -> Unit // Send the 'stopped' analytics event
) {
    // Safely update the current lambdas when a new one is provided
    val currentOnStart by rememberUpdatedState(onStart)
    val currentOnStop by rememberUpdatedState(onStop)

    // If `lifecycleOwner` changes, dispose and reset the effect
    DisposableEffect(lifecycleOwner) {
        // Create an observer that triggers our remembered callbacks
        // for sending analytics events
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_START) {
                currentOnStart()
            } else if (event == Lifecycle.Event.ON_STOP) {
                currentOnStop()
            }
        }

        // Add the observer to the lifecycle
        lifecycleOwner.lifecycle.addObserver(observer)

        // When the effect leaves the Composition, remove the observer
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    /* Home screen content */
}
This is an official example
👍🏾 1
l
Yes, thank you. I've seen it from https://developer.android.com/jetpack/compose/side-effects#disposableeffect. And this is the way I'm using it
l
you're welcome. It looks great. I've learned a lot.
👍🏾 1