1

Recently, lifecycle library has been updated so it should be possible to use it in Compose Multiplatform.

The issue is that I can't get it to work. I try to add lifecycle observer, but when I try to debug, I don't get logs from oncreate, onresume etc. events.

Did someone manage to make it work?

LifecycleEventObserver { source, event ->
    when(event) {
        Lifecycle.Event.ON_RESUME -> {
            println("Hello from onresume")
        }
        else -> { println("Hello from ${event.name}")}
    }
}
0

1 Answer 1

1

I did the below as described in the docs and it worked as expected on Desktop.

Added these dependencies:

implementation("org.jetbrains.androidx.lifecycle:lifecycle-common:2.8.1")
// To make coroutines and flows in lifecycles work correctly on desktop:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.8.1")

Then in my @Composable function:

val observer = remember {
    LifecycleEventObserver { source, event ->
        when (event) {
            Lifecycle.Event.ON_RESUME -> {
                println("Resumed")
            }

            else -> {
                println(event.name)
            }
        }
    }
}
LocalLifecycleOwner.current.lifecycle.addObserver(observer)

OR

val currentState by LocalLifecycleOwner.current.lifecycle.currentStateFlow.collectAsState()
LaunchedEffect(currentState) {
    if (currentState == Lifecycle.State.RESUMED) {
        println("RESUMED")
    } else {
        println(currentState.name)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.