What are some good ways to access a suspend functi...
# coroutines
m
What are some good ways to access a suspend function from Java? My library uses Ktor client to fetch some data, and I want this library to be usable from Java. My current solution is to Java-oriented non-suspending function that uses GlobalScope internally.
1
s
The key is to decide which code will be responsible for handling errors from the asynchronous task, and for cancelling it so it doesn't create a resource leak. If you want the Java code to be responsible, I'd use
GlobalScope.future {…}
to create and return a
CompletableFuture
. If the Kotlin code should be responsible, I'd have the library create and manage its own coroutine scope, and just offer a simple callback on the Java side, or none at all if the function doesn't need to return a value.
☝️ 1
To give the Java code even more control you could also consider a `Mono`/`Single` from reactor/rxjava, but that's probably only a good fit if you're already using one of those libraries
1
b
runBlocking
could also be an option?
r
runBlocking
should be used sparingly, since it totally blocks the calling thread, preventing it from doing any other work. Like Sam suggested, it would likely be better for the function to either receive a callback function or return a future
z
If your library has some kind of longer-lived service object that does these calls, I’d also tie the adapter jobs children to that lifetime, so that if the entire library is disposed (eg in tests) it also cancels any running jobs.
☝️ 1
m
Would MainScope() be better than GlobalScope?
s
GlobalScope never cancels its coroutines, so the responsibility would rest with the consumer to cancel the coroutine when no longer needed and prevent resource leaks. MainScope() creates a scope that can be cancelled. If you use it in a component with a managed lifecycle, and cancel it when that lifecycle ends, your consumer code would be freed from the responsibility of resource management, which could help ensure resources are cleaned up more reliably. If you don't cancel the scope, then no, it's not better.