Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...