Closed buntupana closed 2 years ago
This is expected behaviour since the update.
Please refer to 'flow' documentation or use 'flowOn' instead
The section you need is "Context preservation"
@qwwdfsad I think I'm using the same context val flowContext = currentCoroutineContext()
when I emit so I don't know why is throwing the exception.
I would appreciate if you could give me an example how that code could work in the new version of courotines, thanks!
withContext
creates its own scope with its own Job
in it.
I would appreciate if you could give me an example how that code could work in the new version of courotines, thanks!
.collect { emit(it) }
instead of .collect { withContext(flowContext) { emit(it) } }
@qwwdfsad I've already tried and throws this error:
java.lang.IllegalStateException: Flow invariant is violated:
Emission from another coroutine is detected.
Child of StandaloneCoroutine{Active}@ef4b7c2, expected child of StandaloneCoroutine{Active}@3b89d3.
FlowCollector is not thread-safe and concurrent emissions are prohibited.
To mitigate this restriction please use 'channelFlow' builder instead of 'flow'
Oh, sorry, I misread the snippet.
The simplest option is to use channelFlow
:
return channelFlow {
.
.
.
val flowContext = currentCoroutineContext()
val loading: Job = coroutineScope {
launch(flowContext) {
databaseQuery().map {
if (it != null) {
Resource.Success<T>(it, true)
} else {
Resource.Loading()
}
}.collect { send(it) }
}
}
.
.
.
}
I'm excecuting this code in
Android
:And when I use a version of coroutines above
1.4.2
and worker version above2.5.0
I'll get this exception:Is this a bug or a normal behaviour since the update?
The code will work using these libraries versions: