0

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")
         }
      }
   }
}
kioli
  • 635
  • 1
  • 10
  • 26
  • If this library has to be used in Java, I would provide a "standard" non-coroutine API, with coroutine features provided via extension functions. No one wants to have to work with coroutine contexts and Flows in Java code. – Tenfour04 Jan 26 '21 at 18:46
  • Thanks for the advice Tenfounr04, could you perhaps elaborate on how to achieve that via extension functions (taking into account that internally I would still neet ot use it "as if" it was suspended)? – kioli Jan 26 '21 at 18:54
  • I think typical asynchronous APIs in Java use a callback system and ExecutorService to handle the asynchronous work and running the callback on the calling thread. – Tenfour04 Jan 26 '21 at 19:26

0 Answers0