This message was deleted.
# compose
s
This message was deleted.
a
One way to do it is with LocalComposition
Copy code
class MainActivity : ComponentActivity() {
    private var isStarted by mutableStateOf(true)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            CompositionLocalProvider(LocalIsActivityStarted provides isStarted) {
                MyApp()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        isStarted = true
    }

    override fun onStop() {
        super.onStop()
        isStarted = false
    }
}

val LocalIsActivityStarted = compositionLocalOf<Boolean> { error("CompositionLocal LocalIsActivityStarted not present") }
Someone please let me know if this is a good approach. I use it myself with onResume/onPause so that I can pause a sound when app is put to background
z
I think the best way would be to get the lifecycle via
LocalLifecycleOwner
and then just observe lifecycle changes from that, eg in a
LaunchedEffect
.
a
how to learn LocalLifecycleOwner
a
Thanks for the tip zach. I now use this solution
Copy code
val lifecycleOwner = LocalLifecycleOwner.current
var isInForeground by remember { mutableStateOf(lifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) }

DisposableEffect(lifecycleOwner) {
    val observer = object : DefaultLifecycleObserver {
        override fun onResume(owner: LifecycleOwner) {
            isInForeground = true
        }

        override fun onPause(owner: LifecycleOwner) {
            isInForeground = false
        }
    }
    lifecycleOwner.lifecycle.addObserver(observer)
    onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
❤️ 1
n
I love the Slack search! 😍