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

Jan Skrasek

10/09/2019, 1:04 PM
Hi, I'm trying to consume events from my view-model in fragment and I can't realize why app is crashing:
Copy code
2019-10-09 14:49:52.581 4418-4418/my.app.id E/AndroidRuntime: FATAL EXCEPTION: main
    Process: my.app.id, PID: 4418
    kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelled}@b43ae6d
Copy code
val myEvent = Channel<Unit>(Channel.RENDEZVOUS)

viewModel.myEvent.consumeAsFlow()
	.onEach {
		Toast.makeText(requireContext(), R.string.error, Toast.LENGTH_LONG).show()
	}
	.launchIn(lifecycleScope)
1. it is not obivous what caused the crash from the stack trace; emiting to closed channel? 2. how can I workaround it?
p

Paul Woitaschek

10/09/2019, 1:12 PM
Copy code
lifecycleScope.launch {
  consumeAsFlow.collect { Toast() }
}
a

Adam Powell

10/09/2019, 1:13 PM
1. Looks that way,
consumeAsFlow
will cancel the channel when collection stops, and the lifecycleScope will be cancelled when your fragment is destroyed. 2. What behavior do you want here?
What is the nature of
myEvent
?
j

Jan Skrasek

10/09/2019, 1:25 PM
Actually I'm looking for channel which will deliver the value only once. Hence consumeAsFlow seemed ok. (This is AFAICT different to PublishSubject), so I've tried randevous channel. Though I think it's not ideal (despite the crash) because new activity after rotation can miss the event in the time inbetween.
4 Views