https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

ryan413

08/24/2020, 3:08 PM
When returning a Coroutines JDK Future to a Java library, what’s the best way to do this?
Copy code
fun returnFuture(): CompleteableFuture<String> {
  return runBlocking {
    future {
      // blocking code
      "result"
    }
  }
}
or
Copy code
fun returnFuture(): CompleteableFuture<String> {
    return GlobalScope.future {
      // blocking code
      "result"
    }
  }
}
We have coroutine code further up the chain that then calls GraphQL-java, which in turn is wired with DataFetchers that implement an interface returning a CompleteableFuture. Ideally we want to share the same coroutine context throughout (so we can leverage MDC via
MDCContext
, etc.)
s

sikri

08/24/2020, 3:15 PM
can you share coroutine context between datafetchers and that code with futures?
afaiu, you have 3 layers, with coroutines on sides and with java futures in a middle maybe, you can just create
object DomainScope : CoroutineScope
to at least limit global scope usage
r

ryan413

08/24/2020, 3:36 PM
that’s doable 🤔
we are able to share the coroutine context between the coroutines on both sides, will look further I suppose. Would still need to use either
runBlocking { future {} }
or
GlobalScope.future {}
somewhere in there though
Oh wait, think I misunderstood:
Copy code
DomainScope.future { /* ... */ }
2 Views