If I have a ```suspend fun doWork()``` and want t...
# coroutines
d
If I have a
Copy code
suspend fun doWork()
and want to also wrap it in "listener-form" like
Copy code
fun doWork(onWorkDone: () -> Unit) { 
  someScope.launch { doWork(); onWorkDone() }
}
I fear this might have some thread safety issues. What would be the "correct" way to do something like this? Why I want this: having a public API, where coroutines are an implementation detail. So I don't want to expose
suspend
functions or
CoroutineScope
anywhere.
c
It depends what you mean by thread safety issues. The only possible problem I see is that the
onWorkDone
callback might not necessarily (depending on the scope you use) be executed in the same thread that called
doWork()
.
a
not exposing the public api as
suspend
for something like this is a mistake. If you need java compatibility you can offer wrappers for them into Rx Singles, ListenableFutures, or whatever else, but hiding suspend from kotlin users is going to make everyone's lives harder
☝️ 5
correctly dealing with scoping and cancellation is far harder without the structured concurrency primitives and conventions afforded by
suspend
both for callers and implementers
d
CLOVIS, yes, that was the thought that caused me to ask about safety. Adam, thanks! I initially made this suspend function public, but then got this doubts a-la "what if my users don't want dealing with suspend functions". But you are right, dancing around this turns everything to be complicated...
c
If your API callers are using Kotlin, you definitely should expose the
suspend
functions, as it removes all these thread safety issues and it helps the caller understand what is going on (otherwise, they'd have to wrap your interface into their own). If your clients are using JS, then your solution is safe (JS is single-threaded anyway), if they are using Java or another multi-threaded language then your solution isn't unsafe, it just might be a bit surprising that the lambda works in another thread. It could make it easy for users to write unsafe code, though.
d
yep, that was my main consideration. My clients will be definetely kotlin users, so I will listen to you and Adam and won't do this "listener" overload. Thanks!
👍 2