Hey Kotlin folks - I’ve got a kotlin design challe...
# announcements
j
Hey Kotlin folks - I’ve got a kotlin design challenge, looking for some ideas. I’m building a library that supports java & kotlin teams. The core is naturally Kotlin, but needs to be extensible by both Java & Kotlin. The only real hangup I’ve got is that some of the parts that need to be extended are part of the concurrency model, and I’m using coroutines to get that sweet sweet structured concurrency. Coroutines & java don’t seem to play very nice together. I’m not even talking suspend functions here, just trying to go between java & kotlin or vice versa, aside from the easy translation of completable futures. Anyway, the specific issue: I’ve got some behavior components that are plug able, and may need to do some async tasks. I provide them with a facade to interact with other parts of the system, which seems like a natural place to bridge between coroutines & traditional threading. However, I’m not seeing a way to go from a standard java threading model to coroutines. A coroutine wrapper for Runnable/Callable is trivial though. Thoughts?
s
I’ve done this before and in short it’s tedious and irritating. My solution was to create an
Async
wrapper for my Kotlin API that mirrored the API, but instead used
CompletableFuture
for returns from suspend functions and
java.util.concurrent.Flow.Publisher
to wrap `Flow`s
Unfortunately there’s no
Single
or
Mono
in the current Reactive Streams implementation so you’re stuck with Futures
Also this question would be better in #coroutines
j
yeah, that’s about where I settled. I’m considering relaxing my rigid interop requirement, and allowing some kotlin friendly APis to bleed out by exposing a coroutineScope in my facade API, in addition to my java friendly launch/async ones
s
I agree that this pattern could benefit from some sort of sugar but I’m not sure what that would consist of. Perhaps it could be implemented as an annotation processor.
j
Regarding the #coroutines thing - I realized that after I posted (still new to slack). Is there a way to move/link? How does that work?
nevermind, figured out how to share 🙂
b
I'm not seeing a way to go from a standard java threading model to coroutines.
suspendCancellableCoroutine
/
suspendCoroutine
is the way to transform any callback based model to coroutines
s
You should really use
callbackFlow
to bridge Java -> Kotlin Coroutines for callback-style models. It’s generally not recommended to manually suspend or cancel coroutines.
o
IMO that depends on the callback style -- if it's one-and-done,
callbackFlow
has way more overhead than necessary, and manually suspending is the right way to go
j
hmm… I don’t have it setup as much of a callback model, other than completable futures
j
@bezrukov - I am using the jdk8 library, but again, it really only allows me to go between completable jobs & completable futures