Search code examples
android-jetpack-composeandroid-room

Room data is not updating inside onDispose Jetpack Compose


I am trying to save the HorizontalPager currentPage state in the room database, so was thinking when the composable closes I will save the currentPage value to the database. I did it like this.

DisposableEffect(true) {
    (context as? Activity)?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

    onDispose {
        scope.launch(Dispatchers.IO) {
            vm.updateBookProgress(vm.book.bookId, pagerState.currentPage+1)
        }
        (context as? Activity)?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
}

but the data is not stored in the database, I am guessing that the composable was disposed of so the coroutine was cancelled? I am not sure.


Solution

  • I guess you are true, the coroutine will get cancelled. I suggest you have a globalViewModel or a progressViewModel initiated in the parent compose, pass it in your current compose and update your progress.

    if you are not using ViewModel, you can pass a lambda to your compose from your parent composable and update progress in lambda.

    example:

    @Composable
    fun HorizontalPager(onProgress: (bookId: Int, progress: Int) -> Unit){
        DisposableEffect(true) {
            (context as? Activity)?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    
            onDispose {
                onProgress(20, 10)
                (context as? Activity)?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            }
        }
    
    }