https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

AJ

05/27/2021, 6:54 PM
Hey guys, I’m a bit lost here with the StandaloneCoroutine{Cancelled}. In Android I have an addRepeatingJob call which consumes a Channel from a ViewModel. And in the ViewModel I am sending data to the Channel with :
Copy code
getViewModelScope().launch {
    while (this.isActive) {
        val dateString = calendarInteractor.getDateString()
        dateStringFlow.value = dateString
        log.debug { "sending date string to channel on thread " + ThreadInfo.currentThread() }
        dateStringChannel.send(dateString)
        delay(100)
    }
}
And after going out of the app and returning I am always having a StandaloneCoroutine{Cancelled} for the sending to Channel part, how come? Why does it get cancelled? The launch block is called once and then stops. Any clues would be appreciated
d

dshevliakov

05/27/2021, 7:41 PM
Where does addRepeatingJob come from? Is it lifecycle-ktx method?
a

AJ

05/27/2021, 7:44 PM
Yes. The same behavior is encountered if launch a coroutines with
Copy code
lifecycleScope.launch
in OnResume and then cancel it on OnPause, the coroutine is not launched again OnResume
Seems once the job is cancelled, even if I try to launch a new coroutine it is still cancelled
and the same behaviour if I even create a new CoroutineScope every time
Copy code
CoroutineScope(Dispatchers.Main).launch
or with a job
Copy code
CoroutineScope(Dispatchers.Main + SupervisorJob())
d

dshevliakov

05/27/2021, 8:02 PM
Sorry, it is not clear to me. You expecting that old job will resume?
When you launch new coroutine, I believe, new job is created
Or second time you call
launch
never starts a new coroutine at all?
a

AJ

05/27/2021, 8:03 PM
the second call to launch does not start the coroutine
it does not consume the Channel
Copy code
override fun onResume() {
    super.onResume()
    calendarViewModel.startSendingDateChanges()
    listenToDateSubscription = lifecycleScope.launch {
        calendarViewModel.dateStringChannel.consumeEach {
            textView.text = it
        }
    }
}
this is my OnResume function, which calls the channel populating method and tries to consume it
the data is sent once to the channel and that’s it, nothing is consumed
the first app launch it works and if I go to an another app and back, it stops working
override fun onPause() {
super.onPause()
listenToDateSubscription?.cancel(“Activity paused”)
}
this is my onPause call, which just cancels the Job, basically I am doing by hand what was done by addRepeatingJob
changed to BroadcastChannel and it started working normally, but since BroadcastChannel is deprecated, refactored the whole solution to a StateFlow
d

dshevliakov

05/28/2021, 8:08 AM
Nice. So it was because of channel. It seems your channel completes when there are no more consumers.
3 Views