Home > Net >  How to listen for lifecycle in Jetpack Compose
How to listen for lifecycle in Jetpack Compose

Time:02-25

I am creating an app using the Jetpack Compose. The app does some networking search in the background. I wanted to cancel the search if the user decided to press the back button. so I did it using DisposableEffect.

@Composable
fun SecondScreen() {
    val vm: MainViewModel = hiltViewModel()

    DisposableEffect(key1 = vm) {
        onDispose {
            vm.cancelSearch()
        }
    }
}

I know that onDispose will be called when the composable destroyed. But now the search getting canceled everytime when I rotate the screen. I can understand that because the composable destroyed and re-created.

I wonder if I could some how detect the screen rotation lifecyle, maybe I can prevent this behaviour. Or is there a better way to cancel the search when user press back?

CodePudding user response:

Each reorganization of Jetpack Compose is a life cycle,Detect the horizontal and vertical state during each reorganization,please try

@Composable
fun Test() {
    var status by rememberSaveable{
        mutableStateOf(true)
    }
    LaunchedEffect(LocalConfiguration.current.orientation.absoluteValue){
        status = !status
    }
    Text(text = "is Horizontally $status")
}
  • Related