AG
08/23/2020, 8:57 AMIllegalStateException Flow invariant is violated emission from another coroutine is detected
when running this code, is it possible to fix this without using channelFlow ?
flow<Action> {
val result = downloadFile(url, directory) { event: ProgressEvent ->
emit(DownloadProgress(event))
}
emit(DownloadFinished("path"))
}.onEach { L.d(it) }.launchIn(viewLifecycleOwner.lifecycleScope)
downloadFile method
suspend fun downloadFile(
url: String, fileDir: String, onProgressEvent: suspend (event: ProgressEvent) -> Unit = {}) {
val progressChannel = Channel<ProgressEvent>()
CoroutineScope(coroutineContext).launch {
progressChannel.consumeAsFlow().collect { onProgressEvent.invoke(it) }
}
/* rest of the code */
}
Zach Klippenstein (he/him) [MOD]
08/23/2020, 12:01 PMdownloadFile
to not invoke the callback from a new coroutine. Since presumably "rest of code" is sending something into the channel, why not just invoke the callback directly?Zach Klippenstein (he/him) [MOD]
08/23/2020, 12:02 PMchannel.consumeAsFlow().collect{}
is probably redundant, just do channel.consumeEach{}
or use a for loop.AG
08/23/2020, 1:05 PMAG
08/23/2020, 1:07 PMChannel
in downloadfile method, channel used as an event bus which is passed in okhttp interceptor and when there is a file downloading, it will post values so I can’t invoke callback directly I must listen to channel changesAG
08/23/2020, 1:11 PMflow<Action> {
val flowContext = coroutineContext
val result = downloadFile(url, directory) { event: ProgressEvent ->
withContext(flowContext){
emit(DownloadProgress(event))
}
}
emit(DownloadFinished("path"))
}.onEach { L.d(it) }.launchIn(viewLifecycleOwner.lifecycleScope)
I’m using flow context and then emitting value