I'm writing an Android library and I have a situation (VERY simplified here for example's sake) with an interface where I need to make a function suspended
to be able to call Flow.collect
into it.
interface Executor {
suspend fun <T> execute(flow: Flow<T>)
}
class MyExecutor(): Executor {
override suspend fun <T> execute(flow: Flow<T>) {
flow.collect {
println("execution obtained $it")
}
}
}
class A(val scope: CoroutineScope, val classB: B, val executor: Executor) {
fun executeCommand() {
scope.launch {
val command = classB.getCommand()
executor.execute(command)
}
}
}
class B() {
fun getCommand(): Flow<Int> = flowOf(1)
}
The problem I have is that, when I try to use this library from a test app written in Java I'm not able to properly implement the Executor
interface given its suspended fucntion.
Do you have any suggestion on how to do it?
p.s. A solution would be to make execute
a normal function and provide MyExecutor
with a CoroutineScope
in the constructor, but even if I manage to have a singleton of it for the whole app, it would still be a "nested" scoping, resulting into different workers handling the process.
Although I'm not sure how wrong this is, it sure doesn't sound right
class MyExecutor(val scope: CoroutineScope): Executor {
override fun <T> execute(flow: Flow<T>) {
scope.launch {
flow.collect {
println("execution obtained $it")
}
}
}
}
question from:https://stackoverflow.com/questions/65907076/coroutines-in-nested-scopes