Kotlin API "launchWhenCreated" stops listening for database updates after executing many times

40 Views Asked by At

In my android system service, I am using "launchWhenCreated" to launch a coroutine as observer and it listens for updates from the UI. If UI updates a value, it will be stored in a .pb(protobuf) file, and the observer coroutine will execute a block of code.

// Using LifecycleCoroutineScope

init {
        EventFlow()
        lifecycleScope.launchWhenCreated {
            launch(Dispatchers.IO) {
                create()
            }
            launch(Dispatchers.IO) {
                stateFlow.collect { state ->
                    if(state) {
                        debug()
                    }
                }
            }
        }
    }


private fun EventFlow() {
        lifecycleScope.launchWhenCreated {
            launch {
                mDBRepo.getValue() // <=== This is not executed after UI updates any values.
                    .waitForTrue(stateFlow)
                    .collect { pair ->
                        //Execute this code.
                    }
            }
       }
    }
    

This phenomenon happens properly for most of the time, but there are times when it just stops executing the code block after the UI updates any values. I am sure of this behavior, because I can see the values being updates in protobuf(.pb) file, but I do not see the observer coroutine being executed at all.

If I reboot the phone, it seems to work fine.

0

There are 0 best solutions below