Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

java - Coroutines in nested scopes

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...