Mark function suspend or using builder - kotlin

I'm starting with coroutines in Android app. I'm rewriting callbacks to suspendCoroutine<> {} and I've got one dillema: when should I just mark the function as suspend, and when should I wrap the call in some builder (launch, async, etc.)?
Is there some best practice, rule of thumb, or something?

You should write a suspend fun for every asynchronous, callback-based API call you're currently making.
You should wrap in withContext(myThreadPool) every synchronous API call you're making.
All Android-friendly APIs that do I/O use the async approach, so for these you'll be writing suspend funs, but for CPU-intensive tasks (such as decoding images) you may need withContext.
Finally, to be able to use either kind of calls, you must create a top-level coroutine with launch(UI).
Keep in mind that the above is really just a rule of thumb. When you factor your code, many times you realize you need, for example, a suspend fun to make a CPU-intensive operation because there's a withContext somewhere on that call path.
Let me also add a warning about a very typical misuse of the coroutine APIs: you almost never need async-await. Use it only for the cases where you want to truly run it "in the background" while you continue to perform other stuff in your current context. In simpler terms, you should never write
val result = async { calculation() }.await()
Instead you should write
val result = withContext(myThreadPool) { calculation() }

Related

What is the difference between using coroutineScope() and launching a child coroutine and calling join on it?

I am trying to understand the coroutineScope() suspend function in Kotlin and I'm having a hard time understanding the exact purpose of this function.
As per the kotlinlang docs,
This function is designed for parallel decomposition of work. When any
child coroutine in this scope fails, this scope fails and all the rest
of the children are cancelled (for a different behavior see
supervisorScope). This function returns as soon as the given block and
all its children coroutines are completed.
But I feel this behavior can be achieved by launching a child coroutine and calling join on it.
So for example
suspend fun other() {
coroutineScope {
launch { // some task }
async { // some task }
}
}
This can be written as (scope is a reference to the scope created by the parent coroutine)
suspend fun other(scope: CoroutineScope) {
scope.launch {
launch { // some task }
async { // some task }
}.join()
}
Is there any difference between these two approaches since it looks
like they will produce same result and also seem to work in the same fashion?
If not, is coroutineScope merely a way to reduce this
boilerplate code of passing scope from parent coroutine and
calling join on child coroutine?
TLDR
Using CoroutineScope as in the example adds boilerplate code, is more confusing, error-prone and may handle cases like errors and cancellations differently. coroutineScope() is generally preferred in such cases.
Full answer
These two patterns are conceptually different and are used in different cases. Coroutines are all about sequential code and structured concurrency. Sequential means we can write a traditional code that waits in-place, it doesn't use callbacks, etc. and at the same time we don't get a performance hit. Structured concurrency means concurrent tasks have their owners, tasks consists of smaller sub-tasks that are explicit to the framework.
By mixing both above together we get a very easy to use and error-proof concurrency model where in most cases we don't have to launch background jobs and then manage them manually, watch for errors, handle cancellations, etc. We simply fork into sub-tasks and then join them in-place - that's all.
In Kotlin this is represented by suspend functions. Suspend functions are always executed within some context, this context is passed everywhere implicitly and the coroutines framework provides utils to use this context easily. One of the most common patterns is to fork and then join and this is exactly what coroutineScope() does. It creates a scope for launching sub-tasks and we can't leave this scope until all children are successful. We don't have to pass the scope manually, we don't have to join, we don't have to pass errors from children to their siblings and to parent, we don't have to pass cancellations from the parent to children - this is all automatic.
Therefore, suspend functions and coroutineScope() should be the default way of writing concurrent code with coroutines. This approach is easy to write, easy to read and it is error-proof. We can't easily leak a background task, because coroutineScope() won't let us go anywhere. We can't mistakenly ignore errors from background tasks. Etc.
Of course, in some cases we can't use this pattern. Sometimes, we actually would like to only launch a long-running task and return immediately. Sometimes, we don't consider the caller to be the owner of the task. For example, we could have some kind of a service that manages its tasks and we only schedule these tasks, but the service itself owns them. For these cases we can use CoroutineScope.
By using the scope explicitly we can launch tasks in the different context than the current one or from outside of coroutine world. We generally have more control, but at the same time we partially opt-out of the code correctness guarantees I mentioned above. For example, if we forget to invoke join() we can easily leak background tasks or perform operations in unexpected order. Also, in your case if the coroutine invoking other() is cancelled, all launched operations will be still running in the background. For these reasons, we should use CoroutineScope explicitly only if needed.
Common patterns
As a result of all that was said above, when working with coroutines we usually use one of these patterns:
Suspend function - it runs within the caller context and it waits for all its subtasks, it doesn't launch anything in the background.
Function receiving CoroutineScope either as a param or receiver - usually, that means the function wants to do something with the context even after returning (because otherwise it could be simply a suspend function). It either launches some background tasks or stores the context somewhere for a later use.
Regular function that uses its own CoroutineScope to launch tasks. Usually, this is some kind of a service that keeps its custom context.
At least to me, function which is suspend and receives CoroutineScope is pretty confusing, it is not entirely clear what to expect from it. Will it execute the operation in the caller context or in the provided one? Will it wait to finish or only schedule the operation in the background and return immediately? Maybe it will do both: first do some initial processing synchronously (therefore suspend), but also schedule additional task in the background (therefore scope: CoroutineScope)? We don't know this, we have to read the documentation or source code to understand its behavior. Your second example is unnecessary complication over a simple suspend function.
To further make my point consider this example:
data class User(
val firstName: String,
val lastName: String,
) {
fun getFullName(user: User) = ...
}
This example is far from perfect, but the main point is that it is confusing why we have to pass user to getFullName() if we call this function on a user already. We don't know whether it returns a full name of the passed user, the user we invoked the function on or maybe some kind of a mix? If that would be a member function not receiving a User or a static utility function receiving a User, everything would be clear. But a member function receiving a User is simply confusing. This is similar to your second example where we pass the context both implicitly and explicitly and we don't know which one is used and how exactly.

What mechanism causes a Kotlin coroutine to suspend?

I'm trying to understand kotlin coroutines, I'm coming from C# and there's something I'm not understanding here in kotlin. In this scenario I'm writing a webapi using Kotlin in the Quarkus framework. From what I can tell if I label a controller (or resource) function as a suspend function quarkus will automatically launch it in a coroutine.
The issue i have is i don't know what the preferred method for suspending that coroutine is. The vast majority of examples I see on kotlin coroutines use the delay() function, which internally uses suspendCancellableCoroutine() to suspend the function. That makes sense, but i don't see a lot of example calling suspendCancellableCoroutine() explicitly. I've done some reading about the underlying code that gets generated in a suspend function, and some resources lead me to believe that by virtue of calling another suspend function i'll hit a suspend point and that will suspend my coroutine. In C# i'd usually just call await() from inside my async function to execute the long running code.
In my kotlin setup i have setup an instance of jmeter and i simulate 5 threads calling my API at the same time, while limiting my program to run on a single thread in quarkus. My API then makes a call to another API (i'll call that API, data API from now on), which could be a long running operation. For the purpose of my test my data API has a 1 second sleep in it.
Essentially:
web api controller -> web api processing -> web api calls data api through client -> data API does slow operation
I've tried calling async/await on the call to the data API, which seems to work, JMeter reports that 5 requests are all completed in roughly 1 second, and the logging i have indicates that all 5 requests are handled on a single thread. This feels clunky though. I'm already in a coroutine and now my coroutine is creating a new coroutine (async is a coroutine builder) to execute the long running function.
I've also removed the async/await and updated the call to the data API to be a suspend function as well (though this is a client generated from resteasy client). This also seems to work, but resteasy reactive could be generating something that's doing the suspend for me. I need to work with a simpler example, but in the mean time...
If i'm not using the delay() function in Kotlin, and i'm executing code in a coroutine, what is the preferred method to indicate that a section of code is potentially blocking and my coroutine should be suspended? Do i launch a new coroutine? Call suspendCancellableCoroutine()? Or something else? Probably overthinking this, but i want to make sure i understand this.
The coroutines library provides several suspend functions you can use to suspend in a coroutine or in another suspend function, among them:
withContext
delay
coroutineScope
supervisorScope
suspendCoroutine
suspendCancellableCoroutine
Job.join
Deferred.await
The typical way to convert blocking (long-running synchronous) code into something you can use in a coroutine is to wrap it in withContext(Dispatchers.Default) { } or withContext(Dispatchers.IO) { }. If it's something you use repeatedly, you can write a suspend function for it:
suspend fun foo() = withContext(Dispatchers.IO) {
blockingFoo()
}
but if it's some one-off blocking chunk of code, you can use withContext directly in a coroutine.
Note, using async { }.await() is basically never done. The compiler warns you against it. You should be using withContext instead. Calling await on a Deferred is used either when one coroutine needs a result from some other coroutine that has been passed to it, or when you're working with multiple parallel children coroutines inside a coroutineScope block.
The typical way to convert asynchronous callback-based code into a suspend function so you can use it synchronously in a coroutine is to use suspendCoroutine or suspendCancellableCoroutine. You can look up how to use those. They are pretty low level. Many libraries like Retrofit and Firebase already provide suspend functions you can use instead of the callbacks.
coroutineScope and supervisorScope are for creating a scope inside your coroutine to run multiple children coroutines in parallel and wait for them all.

Is it OK to use redundant/nested withContext calls?

I have a personal project written in Kotlin, and I developed a habit of using withContext(...) very generously. I tend to use withContext(Dispatchers.IO) when calling anything that could possibly be related to I/O.
For example:
suspend fun getSomethingFromDatabase(db: AppDatabase) = withContext(Dispatchers.IO) {
return // ...
}
suspend fun doSomethingWithDatabaseItem(db: AppDatabase) {
val item = withContext(Dispatchers.IO) {
getSomethingFromDatabase(db)
}
// ...
}
You can see a redundant withContext(Dispatchers.IO) in the second function. I'm being extra cautious here, because I might not know/remember if getSomethingFromDatabase switches to an appropriate context or not. Does this impact performance? Is this bad? What's the idiomatic way of dealing with Dispatchers?
Note: I know that it's perfectly fine to switch between different contexts this way, but this question is specifically about using the same context.
You do not need withContext for anything besides calling code that demands a specific context. Therefore withContext(Dispatchers.Main) should only be used when you're working with UI functions that require the main thread. And you should only use withContext(Dispatchers.IO) when calling blocking IO related code.
A proper suspend function does not block (see Suspending convention section here), and therefore, you should never have to specify a dispatcher to call a suspend function. The exception would be if you're working with someone else's code or API and they are using suspend functions incorrectly!
I don't know what your AppDatabase class is, but if it is sensibly designed, it will expose suspend functions instead of blocking functions, so you should not need withContext to retrieve values from it. But if it does expose blocking functions for retrieving items, then the code of your first function is correct.
And your second function definitely doesn't need withContext because it's simply using it to call something that I can see is a suspend function.
As for whether it's OK to use redundant context switching...it doesn't hurt anything besides possibly wasting a tiny bit of time and memory context switching and allocating lambdas for no reason. And it makes your code less readable.

Should a library function be suspend or return deferred

Let's assume I'm writing a library that returns a string which is a complex and long running task.
I can chose between offering this
interface StringGenerator {
suspend fun generateString(): String
}
or
interface StringGenerator {
fun generateString(): Deferred<String>
}
Are there any (dis-)advantages of either of the options and which are they? Which should I choose?
Kotlin coroutines are designed along the "sequential by default" guideline. That means that your API should always expose suspend funs and the user, if and when they really need it, can easily wrap them in async.
The advantage of that is analogous to the advantages of cold flows with respect to hot flows: a suspendable function is active only while control is inside it. When it returns, it has not left behind a task running in the background.
Whenever you return a Deferred, the user must start worrying what happens if they don't manage to await on the result. Some code paths may ignore it, the calling code may get an exception, and then their application has a leak.

Why the *Async naming convention for functions returning Deferreds?

Intellij has an inspection (i.e. lint check) that tells you functions that return Deferred should be named something ending in Async.
Naming conventions like these make sense to me in dynamically typed languages. But Kotlin has such a nice type-checker and ecosystem of tooling, so why rely on the convention?
Especially because Kotlin coroutines bake structured concurrency in, the function will probably also take a CoroutineScope parameter, which would serve the same visual cue at the call site:
suspend fun doStuff() = coroutineScope {
doStuffAsync(this /* CoroutineScope */).await()
//...
}
As a side note, I understand the inspection's message that you'd rarely want a function that returns a Deferred instead of a suspend function. That's not my question. My question assumes that you know what you're doing and you want a Deferred.
To begin with, a function should almost never return a Deferred that comes from an async block. It is up to the caller to wrap some unit of work into an async while doing other work in the foreground, then await on the async result before returning, and wrap all that code in a coroutineScope.
The intended source of Deferred instances is the adaptation layer between Kotlin coroutines and 3rd-party async APIs. For such calls it does make sense to put Async in the name and even some Java APIs follow this convention. For example, you may have a
fun fetchOrder(id: String): Deferred<Order>
and use it as
val orderCancelled = fetchOrder(orderId).isCancelled
This code is type-safe and type-correct, it doesn't cause any compiler errors. It looks like it's fetching an order from a remote system and then checking the order status (whether it's cancelled), but what it's actually doing is getting a Deferred<Order> and checking whether the Deferred is cancelled. Because your function name is missing Async, this kind of error is hard to spot.
Yes, you can also request the IDE to give you the return type, but it may take a while before you even suspect what's going on.
Deferred doesn't return the actual value but is "a light-weight non-blocking future that represents a promise to provide a result later".
As you cannot see this from method name, "we name such functions with the "...Async" suffix to highlight the fact that they only start asynchronous computation and one needs to use the resulting deferred value to get the result".
So the reader of your code can instantly see that your method is not returning the actual value but additionally has to call await() on it.
To your second point about the suspend function:
Usually it's other way round, the xyzAsync() function calls the suspend xyz() function.
As functions returning Deferred can be called from anywhere, not only from suspend functions.