I need something to run each time the window gains focus but I notice that the first time the screen is shown
WindowInfo.isWindowFocused
remains false. Only when switching away from the app and returning, does this property become true. I also noticed someone else reported this a few years ago: https://issuetracker.google.com/issues/186226793 (Android)
Mark
02/17/2024, 8:37 AM
My workaround
Copy code
@Composable
fun WindowFocusObserver(onWindowFocusChanged: (isWindowFocused: Boolean) -> Unit) {
val isWindowFocused = LocalWindowInfo.current.isWindowFocused
var isFirstTime by remember {
mutableStateOf(true)
}
val callback = rememberUpdatedState(onWindowFocusChanged)
LaunchedEffect(isWindowFocused || isFirstTime) {
// note: cannot change isFirstTime in snapshotFlow so change here instead
val overrideValue = isFirstTime
isFirstTime = false
snapshotFlow { isWindowFocused || overrideValue }.collect { callback.value(it) }
}
}