Kotlin Coroutines Full 4-Hour Course

00:00:00 - 00:00:58
Kotlin coroutines are an incredibly powerful abstraction when it comes to building concurrent systems that perform well. But to really make the most of them, you need to develop a good understanding of how coroutines in Kotlin work. That is why together with the Kotlin coroutines team, we have decided to build this workshop so that you can develop a better understanding and become productive with coroutines in Kotlin as fast as possible. My name is Sebastian. I’m one of the developer advocates for

00:00:29 - 00:01:22
Kotlin here at JetBrains, and I look forward to spending the next couple of hours with you diving into the nitty-gritty of everything that coroutines has to offer. Throughout this course, we will be talking about all major subjects that are related to coroutines. We’ll talk about coroutines in general, then we’ll dive more deeply into the structured concurrency paradigm and how error handling works in coroutines. And then we will move on to talk about the reactive abstraction that we have in

00:00:55 - 00:01:51
Kotlin coroutines called flows. After going through the contents of this workshop, you should have everything that you need to become productive and use coroutines in your production applications. So let’s get started. Parts of this course are also designed to be interactive. So at certain points, you will have the opportunity to take some of the things that you’ve learned in the previous sections and put them into practice yourself. In the accompanying repository of this course, there are a number of small apps that

00:01:23 - 00:02:24
you will be able to work on. This includes our articles app, a small simulation of a water kettle, and a chat example as well. And we’ll work through all of these. Of course, you will also get all the solutions right in context. Okay, with that out of the way, it’s time to take a look at some of the basics of coroutines in Kotlin. First, let’s try to establish a bit of a mental model of what coroutines really are. A helpful metaphor that you will often hear is that coroutines are like

00:01:53 - 00:03:02
lightweight threads. But what does that mean specifically? Well, if we take a look at a thread, a is simply just a sequence of instructions which are executed sequentially within that individual thread. You can have multiple threads that can run concurrently. And as long as data is confined to a single thread, it can be accessed safely without the need for synchronization primitives like locks or mutexes. Contrary to that, if you are sharing state or mutable data across multiple threads, you need to be

00:02:28 - 00:03:26
careful to make sure that you use the correct synchronization primitives. We can easily switch out the word thread for coroutine in all of these sentences and they still stay true. A single coroutine is still just a sequence of instructions that are executed sequentially. You can have multiple coroutines that can all be executed concurrently. As long as you have data that’s confined to a single coroutine, it can still continue to be accessed safely without requiring any kind of synchronization primitives like locks or

00:02:57 - 00:04:00
mutexes. And when we begin to share state across coroutine boundaries, we need to take a little bit of extra care. Coroutines are a very lightweight abstraction that run on top of threads. So while your program might have a couple of thousand threads running at the same time, it is no problem for your program to manage multiple millions of coroutines which are running on top of those carrier threads. An individual coroutine runs on one thread at a time, though depending on circumstances, it may switch which carrier thread it is

00:03:29 - 00:04:29
running on. Note that despite this, the same visibility guarantees continue to exist within a single coroutine. You can still see all the information and data as well as all the behavior that has happened before a certain point in time. But it is also important to note that coroutines are more than just lightweight threads. There are a couple of things that make coroutines unique and a more powerful abstraction for you to use in your applications. They are a complete toolkit for managing shared

00:03:58 - 00:04:57
state and concurrent computations. They also have the concept of structure concurrency built right into the core of all of their abstractions. And as we go through the course today, you will see what an important abstraction this is and how much it can help you with building systems that work well even in the context of errors. On top of that, the coroutines toolkit also gives you the reactive style abstractions which we call flows, which is an additional extremely valuable programming paradigm.

00:04:28 - 00:05:28
Before we start writing our first own coroutines-based code, let’s first talk about a couple of the core concepts and core vocabulary that we’ll encounter throughout this course. Starting with the most basic building block of any coroutines-based code, the suspending function. A suspending function, which is just marked with the suspend modifier, is simply a function that can pause. That means it has a built-in mechanism that allows it to temporarily stop execution and resume at a later

00:04:58 - 00:05:59
point. This is the fundamental building block of the coroutines machinery and is something that we’ll see quite a lot over the next few hours. A coroutine itself is then an instance of a suspendable computation, which also has its own lifecycle. The coroutine scope is a mechanism for grouping together multiple coroutines, which will be particularly important when we start talking about structured concurrency. The coroutine context, on the other hand, is just a bag of special values that is associated with a given

00:05:29 - 00:06:25
coroutine. And then there is the concept of structure concurrency, which simply means that you get the power to manage entire hierarchies of coroutines and handle errors predictably. We will spend a significant part of this course talking about structured concurrency in detail. Moving on, there are two additional phrases that I would like for us to disambiguate before we move on. There is the phrase of concurrency and parallelism. These are closely related, but they do mean slightly different things, so it’s useful to talk about

00:05:57 - 00:06:59
this once in advance. Concurrency is the idea of managing multiple tasks simultaneously, though this does not mean that they need to necessarily happen at exactly the same time. You can think of this as intertwined execution. You can contrast this to parallelism where multiple tasks are running on multiple threads simultaneously. So they are running literally at the same time. And here you typically have the ability to leverage multiple CPU cores and that can also help you with getting increased

00:06:28 - 00:07:25
performance out of your code. These two are closely related, but they are not exactly the same. Here is a small visualization that might help you understand the differences. On the left side, we have a concurrent process. We have a red, a purple, and a blue task that all share the same thread, but just take turns being executed. In this case, we call this interleaved execution. So we have multiple tasks that take turns sharing the same underlying carrier thread. In the parallel case, we can see

00:06:56 - 00:07:58
that we have three threads that are working simultaneously on three different problems. Real code can be concurrent, it can be parallel, or it can also be concurrent and parallel at the same time. Now let’s move our focus to coroutines in Kotlin. The fundamental statement that I would like for you to understand is that coroutines are computations that can be suspended. Where a thread is blocked while it is, for example, waiting for the result of an API, a coroutine is suspended. So it pauses execution, but frees up the

00:07:27 - 00:08:28
underlying carrier thread. Well, let’s take a brief look at an example. Here we are using my http service.load articles to load some article data from some sort of remote service. Let’s assume that load articles is implemented as a blocking call. As such, on whatever thread we call load articles, on this thread, we will not be able to do any kind of other meaningful work until the HTTP service returns the value. The thread is blocked and it cannot be occupied with any other tasks in the

00:07:58 - 00:08:52
meantime. You probably have an idea where this is a particularly big problem, which is when you do this on a UI thread. By doing long-running blocking operations on a UI thread, the UI will simply freeze and the user will have an unresponsive application on their hands. Now let’s take a look at what this same code snippet might look like if we had implemented it in coroutines. Well, I’m sorry to disappoint, but it actually looks quite similar. The only small difference that you might be able

00:08:24 - 00:09:21
to tell is that we have a small suspend icon in front of the line of code. Apart from that, it’s mainly an implementation detail here. By changing the underlying implementation of load articles to be a suspending function, it no longer blocks the underlying thread and is free to do something else. And this is precisely one of the superpowers of Kotlin coroutines. Without changing the shape of your APIs too much, you gain real tangible benefits in the way that you can express your code in a way that

00:08:53 - 00:09:52
still does not block underlying threads. Because instead of blocking the thread, we simply suspend the coroutine that is executing this code. So we move the coroutine off the thread somewhere else. We put it into a suspended state and until the coroutine resumes from its suspension, the thread is free to work on other meaningful things. Of course, besides coroutines, there are a number of other frameworks on the JVM that also allow you to manage concurrent code. So let’s take a brief look and see what the

00:09:23 - 00:10:23
difference between those and coroutines are. First, let’s start with the baseline case, a blocking implementation of a small flow of operations. Here we have three functions, login which returns us a user ID, load user data which takes that user ID and gives us some user data, and show data which takes the user data and then show something on the screen. In the most simple implementation, what we would want to write is something like we want to log in first to get the user ID and then we want to load user data given

00:09:52 - 00:10:57
that user ID and then show it. Without doing anything else, those implementations are probably blocking. But the good part is that the code is very straightforward and quite easy to read. Let’s compare this to an implementation based on completable future. With completable future, the signatures of our now change quite significantly. Login, now login async, returns us a completable future of user ID. Uh load user data async uh returns us a completable future of user data. And now the implementation of show user info

00:10:25 - 00:11:28
also needs to significantly change its shape. We need to use operators like then compose and then accept to get the same behavior that we had previously. As you can probably tell, this requires a bit of mental overhead compared to the straightforward implementation. If we look at an RxJava implementation, we probably would come up with the same kind of concerns. Now login and load user data return singles of user ID and user data objects. And our show user info function still needs to use operators like flat map, do on success,

00:10:56 - 00:11:55
and then finally call subscribe in order to get the same kind of behavior. So can coroutines do better? Well, let’s take a look. The main difference that we see comparing this to the blocking implementation from the beginning is actually just that suspend modifiers have been added to the login, load user data, and show user info functions. But the actual logic of the implementation of show user info stays the same. We can continue writing sequential code, but we can still get all of the benefits that

00:11:26 - 00:12:22
we get from writing non-blocking code. That’s the power of using suspending calls instead. So in short, with coroutines, you can write code that looks sequential, but you don’t incur any of the drawbacks of writing blocking code. And that’s pretty powerful. So with this, we already have a very basic understanding of what coroutines are and how they change or don’t change the shape of code. Let’s actually go hands-on. Over here in IntelliJ, I already have taken the liberty of

00:11:53 - 00:12:55
opening up our accompanying project for this course. Let me just start that up for you so that we can see what we’re working with. When you run the launcher run configuration, uh you will see that a small window pops up which allows you to select from a couple of applications that we will be working with throughout this course. It also tells you that the underlying server, which provides some data that we will be working with, uh has started on port 9020. Let me open that up here for a second. So as we can

00:12:24 - 00:13:37
see here, uh there is a small embedded server courtesy of Ktor uh running inside of our small application that allows us to get some data out of it. For example, we might visit the articles endpoint and we can see uh that there are a couple of articles with their title, their author, and ID. There are also comments that are associated with each article. So for example, for the article one, we can see that there are admittedly not very creative comments one through six uh from different authors. Now let’s

00:13:02 - 00:14:03
take a look at our articles application, which is designed to work with the information from this API. It looks like this. It has a small liveness indicator up here, which is just a small smiley that is turning. It has a number of different loading modes. And as we go through the course, uh we will be implementing these different types of loading modes. It has a load comments button, which once we have properly implemented things, uh should pop out the information from author, title, and the number of comments down

00:13:33 - 00:14:41
here. And it also has a cancel button that allows us to see how coroutine cancellation works in action hands-on. Our first task will be to implement the blocking and suspending implementations of this loading mode. We don’t have to write any of the network code ourselves, thankfully. That’s already provided as part of the application. There is a blocking implementation of the blog service, which is based on Retrofit. Retrofit also has suspending implementations. So this is not a dig at Retrofit. It’s just that we try to use

00:14:07 - 00:15:07
it here for this example. And we also have a blog service implementation which provides functionality based on Ktor. So based on coroutines and functions. I am only showing you the implementation here for reference. Uh it is not required to understand the exact details of how things are implemented, though you are of course welcome to explore. Our first task begins in the file task one block versus suspend. Here you can find a couple of functions that you can implement. Once you’ve done the implementation of

00:14:37 - 00:15:39
the stubbed out functions in this file, you should be able to restart the application and use the UI in the suspending and blocking modes to see the actual information trickle into our UI. This might be a good moment to pause this video and give this a shot yourself. All right, let’s take a look at what these implementations might look like. To solve this task, we can let ourselves be guided by both the parameter that we get, service blocking here, and the return type that is expected, a list of article.

00:15:08 - 00:16:19
So we want to create some article objects which require article info and comments. So where do we get the article info from? Well, we can get the get article info list function that already looks pretty good. So article info and then we probably want to map this. So we’ll map each one of these into an article. And we still need to get the comments. So we might still grab ourselves the comments and it seems that service blocking also allows me to get the comments for a given article info object.

00:15:44 - 00:16:40
So we can add these as well. Now all we have to do is make sure that we actually return this value and we have an implementation. Before we move on to the suspending implementation, let’s see if this actually works. I’ve started the application and I’m opening the articles app. I make sure that the blocking mode is selected and then I’ll hit load comments. After a short while, we can see some things happening in the background here. We indeed get some UI overview. We see that eight articles were loaded in

00:16:12 - 00:17:24
roundabout nine seconds. Perhaps perhaps in staring at this, we also noticed a bit of an issue, and that is that our little spinny friend up here uh stops moving. And even the small animation that’s happening over here uh is not updating properly while this operation is happening. And only once the entire operation is done uh does the UI become responsive again. This is a pretty direct visualization of the problem that we have when we build implementations that are blocking that end up running on the UI thread. The UI

00:16:48 - 00:17:50
thread is busy trying to get data back from some sort of remote API, and it’s not free to do anything else like redraw our little smiley friend here. So let’s see if we can do better. I’m going to close the project and we’ll figure out the implementation using the regular service. You may remember from a few minutes ago that one of the main benefits of coroutines is that you can write code that looks sequential without the downsides of blocking. So hopefully it does not come as a

00:17:19 - 00:18:17
surprise that I can take the exact same code for the previous solution and replace service blocking with our service. The main difference, like in the example that we looked at in the slides, is that now we have an implementation that it itself is suspending. We can also see a little suspend icon indicator here uh that shows that we’re calling a suspend function. But the shape of the code hasn’t changed, so we didn’t need to solve the problem in any other way. We could write the most straightforward

00:17:49 - 00:18:46
code that uses Kotlin collections to achieve the exact same thing. Let’s start our program one more time. After the server is started, I will switch the loading mode to suspending. And now watch our little smiley friend up here. As I hit the loading button and even the spinner down here, both of them keep rotating happily even though there’s clearly some operation happening in the background. And then after everything is done, we get our eight articles loaded in 9.1 seconds. A lot nicer, right? So here we

00:18:18 - 00:19:14
just saw once again that with coroutines you can write code that looks sequential without any of the drawbacks of blocking. The core primitive that makes all of this possible is the suspend function. It’s a function that can pause. This is actually a concept that is built right into the Kotlin compiler. So the Kotlin compiler understands how a function should be transformed in order for it to be able to pause and later resume execution. We call this pausing of execution of the code without blocking the underlying thread that it

00:18:46 - 00:19:49
can trigger suspension. Now there is one important nuance which is that suspend functions can’t just be called from anywhere. There are specific places in which they are allowed. Most directly a suspend function can be called from another suspend function. Taking a look at the exercise that we just solved, we saw that the load articles function that took the blog service so that was the suspending implementation itself was also marked as suspend. Had we not provided this modifier well we would have seen an error because

00:19:18 - 00:20:25
suspend functions can only be called from a coroutine or another suspend function. So you might be asking how far does this go? And indeed you can actually do this all the way up your call hierarchy with even your main function being marked as suspend. That’s still possible. Here you can provide a suspend lambda and that code will be executed in the context of the coroutine. And for very special cases where you find yourself in a situation where you have existing blocking code and need to call suspending functions, there is also

00:19:51 - 00:20:54
a bridging function that allows you to fill the gap between blocking and suspending worlds. Fundamentally the idea of saying well a suspend function can call any other regular function but a suspend function can only be called from within another suspend function. That is the concept of function coloring if you’ve ever heard of it. Just as a little aside. So in our exercise we had a small suspend function. We didn’t really care about who called it or in what way it was called but now it’s time to dig a

00:20:22 - 00:21:20
little bit deeper and understand how we generally enter the world of coroutines. Most basically, like I already mentioned, you can simply specify your main function to be suspend. You write suspend fun main and that’s it. And then, of course, there is the entire world of coroutine builder functions that allow you to create instances of these kind of computations that can suspend. We’ll take a look at a couple of them, though note that this list is non-exhaustive. And we’ll start with one

00:20:51 - 00:21:53
that’s quite basic but still very, very important, the lowercase c coroutine scope function. This itself is a suspending function. So if you are in suspend fun main, you can call this lowercase c coroutine scope function. We call it a lexically scoped coroutine builder because all the work that you do in the lambda block that’s associated with it lives for as long as the block lives itself. We’ll see what that means in detail later. The other important part to note is that the lambda block itself is a new

00:21:22 - 00:22:28
coroutine. We can see this because it introduces the receiver type of coroutine scope. And this is quite significant as we will see literally right now. Because next on our list of coroutine builders is the launch function or, as we should say more accurately, the extension function on the coroutine scope interface called launch. Why does this distinction matter? Well, because it gives us the understanding of where we are allowed to start a new coroutine using the launch coroutine builder. We can’t just call it anywhere where we

00:21:55 - 00:22:55
are in a suspend function. We already need to be in the context of another coroutine scope, like we are when we use the lexically scoped coroutine builder coroutine scope that we have above. Launch too is a coroutine builder, so it itself provides you with a new coroutine and that coroutine has its own coroutine scope associated with it again as well. The launch coroutine builder is designed specifically for start and forget style coroutines. So something where you start some code in the provided suspend

00:22:25 - 00:23:37
lambda, it runs, but it does not return you a specific result. Rather, you are observing some sort of effect or change in the overall system. We can contrast this to the async coroutine builder or, once again, the async extension function on coroutine scope. Like launch, a coroutine scope already needs to be in scope for you to be allowed to call async. And like any coroutine builder, it too creates a new coroutine, so it itself once again gets a coroutine scope as the receiver type for its lambda. Async is special in that

00:23:01 - 00:24:02
it allows you to wait for the result of a computation from a coroutine. As we will see in a little bit, it returns you an object of type deferred of a generic type which you can await. So you can wait for the computation that has been done in a separate coroutine. For the special case of changing the coroutine context, there’s also the specialized with context coroutine builder. It too creates a new coroutine scope, and like the coroutine scope lowercase function, it itself is also a suspending function,

00:23:32 - 00:24:24
and it too is lexically scoped. While this may seem like a lot of information all at once, I just want to give you a high-level overview of some of the pieces that we will snap together later on even in action. One function that I want to separate out a little bit here is the run blocking function. While you may encounter this every once in a while, it is really a specialized function that is just designed to block a thread until a bunch of coroutines are done. We’ll talk more about run blocking

00:23:58 - 00:24:53
in detail a little bit, but for now I just want you to understand that this function has a number of caveats that typically mean that other functions are a better solution. So we have a high-level theoretical understanding of what’s going on with coroutines and coroutine builders. Now it’s time for us to actually put this into practice. Here I am in a standalone Kotlin file with its own main function, and all I’ve done is I have added a little workshop service implementation that just gives

00:24:25 - 00:25:29
us a couple of functions that we can call to demonstrate what’s going on. First, let’s start quite basic. Let’s say I have a function that returns me a result, so I’ll just make a service network call. Well, because this function in itself is implemented as a suspend function, I can’t just call it from anywhere, so I can’t just call it from my main function here. Uh instead, I need to make my main function suspend or I need to find myself in some other context in which suspend functions are allowed. Once I

00:24:58 - 00:25:57
have done this, I can continue writing my sequential code. For example, I can use our slightly specialized log function to print the result of this network call. All that this log function does over a regular println is that it just adds the current time, the current thread, uh and then whatever text we have. So running this, we can see that our application is sending a request and then it is receiving a result and that result is indeed logged. We can see that we are working with coroutines here

00:25:27 - 00:26:28
because we have this little suspend function indicator over on the left-hand side. This indicates that a function marked with a suspend modifier has been called on this line. To provide more detailed information in the log messages about where and how our coroutine is running, I’ve actually already gone and pre-parameterized the run configuration with the Kotlinx coroutines debug virtual machine option. This adds a little bit of extra metadata that you will be seeing down here. A basic suspend function is, well, basic, so

00:25:58 - 00:26:58
let’s move on to using some of the coroutine builders, starting with the launch builder. If if you recall from our previous discussion, I can’t just call launch in my suspend fun main function. Why? Because launch is an extension on coroutine scope. So I need to use a suspend function that gives me this coroutine scope. Well, it was the first builder that we’ve ever talked about, which is the lowercase coroutine scope builder. Since I have a lot of inlay hints enabled, you can see here that the

00:26:28 - 00:27:33
receiver type of the lambda is indeed of type coroutine scope, the interface. And in here, I can absolutely call launch. Recall that launch coroutines are designed for running some sort of code, but not really returning a specific result. So I might grab my service again, I might make a network call, and I might just log this information. And of course, one of the main motivations is that I can start more than one coroutine at a time that will run concurrently. So I can start a second coroutine here as well.

00:27:01 - 00:27:59
And instead of making the exact same network call, let’s have it make another network call. Let’s run this. Looking at the output, we can see that indeed there are multiple things happening at the same time. We get the network request sent for both of our coroutines before the results are trickling in. So we get one result and we get another result that is printed each. Here we can also see a little bit of the lexically scoped behavior of the coroutine scope builder. In fact, it uses the concept of

00:27:30 - 00:28:26
structured concurrency, that we’ll dive into much more later, to make sure that it actually waits for the completion of all the coroutines that were started in this coroutine scope. So I did not have to add any kind of delay at the end of our application to make sure we actually see the results. Coroutine scope waits for completion of all of its child coroutines. This is perhaps a good place to shout out that launch and async are indeed builders. So they start something and then the code continues running. Let

00:27:58 - 00:29:17
me make this even more clear. Let me pause or delay the execution of these coroutines by 200 milliseconds each, and then let me log continuing afterwards. Looking at the output of this code, we can see that continuing happens first, or we see continuing first. Why? Well, because the coroutine scope starts execution, it launches one of the coroutines which is scheduled to be executed and waits. It does the same for the second one, and it continues running its own code block. So first we see continuing and then as operations happen

00:28:37 - 00:29:44
in each of the coroutines, they speak up in our logs as well. While the launch coroutine handler does not give you a result in the classical sense of a computation, it still gives you a handle on the coroutine that you can use to do things like wait for it or cancel it. This is the job that is associated with this coroutine. So we can have our two jobs here for example, and if we wanted to, after already 100 milliseconds, we could change our mind and use the job to for example cancel the first coroutine. So

00:29:10 - 00:30:25
after re-running this code, we can see that because our first job was launched, started to delay, but was canceled before any operation could actually happen, the only output we see in our logs is the other network request and the other result. So this job handler can be used to for example cancel a coroutine. Let’s move beyond launch and look at sync next. Consider these lines of code here. I have a user ID which I get from a service by logging in. I get some shop info which loads shop info also from the service and then

00:29:47 - 00:30:53
I want to create a full list of orders which requires both the user ID and the shop info and then probably I want to log this information somewhere. We can run this code and it operates just as expected even though this specific person has not made any specific orders, but it does run. And it once again shows us that for the most basic case you can simply write sequential code with coroutines that doesn’t block. But upon further investigation we might notice that the service login call and the service load

00:30:20 - 00:31:16
shop info call do not depend on information from each other. So that is a pretty good indicator that they can be executed concurrently. And instead of first waiting for the login to be done and then loading the shop info, it might save us some precious time by doing both the login and the load shop info at the same time. This is precisely one of the cases where the async builder would be perfect to use. We remind ourselves that async is also an extension on coroutine scope and we validate that we do indeed have a

00:30:48 - 00:32:11
coroutine scope, well, available to us right here. Now we can just wrap the block for the service login call and for load shop info. We can see that the return type now changes. Async returns us a deferred of whatever type we got back from our call here. This is equivalent to, for example, a promise or a future in other languages. And the main thing that you can do with a deferred is you can await it. So now we can just await both user ID and shop info before we pass it to load orders. And running this once again, it

00:31:30 - 00:32:33
executes all the same. But this time we can very clearly see in our log that login and loading shop info starts before the user information was properly retrieved or before the shop info has completed. So we have two things running concurrently, then we wait for both of the results and we continue working. While we already have a couple of these coroutine builders on screen, this might also be a great opportunity to tell you that these can also be parameterized. The most important parameter here is the

00:32:01 - 00:33:06
coroutine context. We will talk about the mechanics of coroutine context in much more detail later, but for now you can, for example, pass a coroutine name to this coroutine that identifies it, like the login coroutine. When we’re running this and scrolling through, we can see that the login coroutine is now identified as such in our logs, which might be helpful for debugging, for example. So you can put name tags on coroutines. This context parameter is also where you would, for example, specify dispatchers if you would want

00:32:33 - 00:33:35
to. Again, a topic that we’ll talk about a little bit more in in a tiny bit. So at this point, we have made our first experiences in writing our own standalone coroutines code. We’ve also used the special flag Kotlin X coroutines debug to add additional information like coroutine names in our debugging information. With all of this experience under the belt, it’s probably now a good time to recap once again the individual mechanics for each of the coroutine builders. We have seen how coroutine scope is used

00:33:04 - 00:34:07
in practice already. It itself is a suspend function. So wherever you call coroutine scope, the calling code will pause. It will suspend until whatever is happening in the lambda that you provide has completed execution. If you are calling plain suspend functions right within that lambda, well, it certainly waits for them and it executes them top to bottom. One of the key features that it provides you is that it provides you this coroutine scope as a lambda receiver. And that matters precisely because

00:33:36 - 00:34:38
launch and async are builders that are extensions on coroutine scope. Through the power of structured concurrency, it actually waits for the completion of all of its child coroutines. Because the coroutine scope function acts like any other scope function in Kotlin, it can indeed also return a value. More formally, you could say that coroutine scope is used for the concurrent decomposition of work and it is lexically scoped. So it allows you to start a bunch of new coroutines. Those will compute something or do some work.

00:34:07 - 00:35:07
The coroutine scope function itself will wait for its completion and may optionally then return a result to its caller. Here it is once again in code. We can call suspending functions directly like delay at the top. We can start new coroutines using launch, for example, that will do some sort of operation. Coroutine scope will wait for their completion and will return the last expression in its block like any other scope function to its caller. That’s how the val result in the very first line is

00:34:37 - 00:35:34
the string result value at the end of execution. Moving on to the launch coroutines builder, which once again is an extension on coroutine scope. This one starts a new coroutine without actually suspending, and you get a reference to that coroutine as a job. You can use that to do things like cancellation, for example. Most importantly, since it does not return a real value, you typically use this in the start and forget types of scenarios. You’ve seen the snippet in practice just a moment ago.

00:35:05 - 00:36:02
The async coroutine builder, which is also an extension on coroutine scope, is quite similar in some respects to launch in the sense that it also does not suspend, and it also starts a new coroutine. The key difference once again is that it returns you a future result as an instance of deferred. Specifically, this is actually a subtype of job. So you can still use that deferred, for example, to do things like cancellation. Um it’s analogous to future or promise in other languages, um and you can use

00:35:34 - 00:36:30
it specifically to kick off multiple computations and then run those concurrently. Once you’ve gotten a hold of a deferred, uh like we had in our previous snippet, well, the main thing you can do is you can call await on it. Once again, await is implemented as a suspending function, of course. So it waits for the completion of the value without blocking the underlying thread. After all, that’s one of the key points why we’re doing all this. The invocation of await resumes when the deferred

00:36:01 - 00:36:58
computation is finished. So by now you may have noticed a little bit of a pattern, which is that when we are working with coroutines, often times these job objects keep popping up. And in fact, each coroutine has a job associated with it. The job object actually takes quite an important role. And when we talk about structured concurrency in detail, we’ll see how job will actually return as part of the coroutine scope mechanics. But to give you a little bit of a preview, it is actually the object that

00:36:30 - 00:37:33
keeps track of parent-child relationships in coroutines. It is also the handle that we use for cancellation of individual coroutines, but also of subtrees of coroutines. And we will see that all coroutine builders launch async, the lowercase coroutine scope function, they all create a new coroutine scope uh that contains and also exposes a job object in some way. With launch, you get the job directly as the return value. With async, you get a deferred which inherits from job, so it’s a special type of job with a

00:37:01 - 00:37:56
result. We will dive a lot deeper into this when we talk about structure concurrency, including a bunch of visualizations that hopefully make understanding this even easier. Before we move on to the next tools in our coroutines toolbox, I want to spend a little bit of time talking about async and await in a context that is maybe helpful for you if you are coming from a different language background. For example, if you come from a background of JavaScript, you might be used to declaring a function using the async

00:37:28 - 00:38:24
modifier and invoking it by prefixing the invocation with await. If you have written Python or C# before, uh you might also be used to this pattern where you prefix things with async and then when you call things, you await them. In Kotlin, we have a different approach to writing functions where we still expect the code to be executed sequentially from top to bottom, but we want to be able to wait for the results of other functions. In Kotlin, async and await are reserved for those cases where you

00:37:56 - 00:38:56
want to start multiple tasks and then at some later point await their results. Otherwise, suspending functions are still the top choice. If you have code that does not explicitly need to work with deferred objects, right? So cases where you really need a future or a promise, don’t reach for async. Just reach for suspend as the more basic primitive. Like I have said a couple of times by now, suspending functions are the core primitive that allow you to write code that can pause execution. Suspend

00:38:26 - 00:39:29
functions like any other functions can still return values once they complete, but for the basic case of where in the next line of code you’re interested in what the previous line of code has done, you don’t need to work with anything like deferreds. This slight paradigm shift may take some getting used to, but if I may speak from the heart here for for just a second, for me it was always quite confusing why there were two keywords in a language, async and await, to express simply the ability to pause execution. Once you

00:38:58 - 00:39:56
have embraced the idea of just a function that can pause with suspend, I think you’ll find that it is quite a good abstraction. Before we wrap up our overview of coroutine builders, I want to spend a couple of moments talking about the specialized bridging function run blocking. You may have seen this out there before, so it’s important that we also cover it here. Run blocking is designed to start a new coroutine. We can see this because it gives us a new coroutine scope receiver in the lambda

00:39:27 - 00:40:26
block that we provide, and it then blocks the current thread until its completion. At first, this might seem a little bit counterintuitive because we’ve been talking and talking about how we do not want to block a thread when we are using coroutines. So why is there a function now that does indeed just block a thread? The important part to note here is that it blocks one thread, but it allows you to start an arbitrary number of coroutines on that thread or, with the power of dispatchers, on other threads as well.

00:39:56 - 00:41:06
Like the lowercase coroutine scope function that we’ve used previously, it too waits for suspend function invocations and it waits for coroutines launched inside. So it too creates a lexical scope. However, its use case is much more narrow than the coroutine scope function. Run blocking is specifically designed for scenarios where you have blocking code and you need to invoke non-blocking code. What makes run blocking special is that under the hood it effectively builds an event loop on top of the carrier thread that you’ve

00:40:31 - 00:41:32
called it on. So the thread gets blocked and then each of the coroutines that you start as part of this run blocking scope, they get added to a task queue. The carrier thread then works through the task queue, either running a coroutine in its entirety or running a coroutine up to a suspension point, putting it somewhere else, working on something else, that’s interleaved computation again until everything is done. Hopefully, from this explanation, you can tell that by default, unless configured in any other way, the

00:41:01 - 00:42:04
invocation of run blocking is actually single threaded. So if we are thinking back to the terminology that we introduced in the beginning, this is a concurrent process, but it is not necessarily parallel here. But most importantly, we can see that run blocking does some special things. It specifically creates this task queue for the carrier thread. As such, it is really not designed to be general purpose. It’s designed to bridge the world between blocking and non-blocking code. And it itself, unlike coroutine scope,

00:41:32 - 00:42:34
is a blocking function. It blocks the thread. So using run blocking inside of a function that is already marked as suspend is a really bad idea. And IntelliJ will actually tell you that that’s not a good idea. The general advice when you find yourself reflexively reaching for run blocking is to see if you can’t use coroutine scope instead. Run blocking is really only preferred in scenarios where you have no choice and need to bridge the world between blocking and non-blocking code. By now, it really is high time for us to

00:42:03 - 00:42:59
write a little bit of coroutines code ourselves again. I am back in our articles app here again. And when I hit load comments, I’m actually noticing a behavior that’s kind of odd. It takes quite a long time for these articles to load. In fact, it takes 9.1 seconds. Surely with the new knowledge of coroutine builders, we can do a little bit better than that because so far the implementation that we built was the most straightforward one. We wrote sequential code that didn’t block the

00:42:31 - 00:43:41
caller thread. But so far, we’ve not started any new coroutines that actually run and do things concurrently. But now you are equipped with all the tools to build exactly this in the task to sequential versus asynchronous file, which you can find in the tasks package of the desktop client project. You can find a stub which asks you to implement the concurrent loading of articles. To validate that your solution is correct in the articles app, make sure that you switch the loading mode to concurrent and hit the loading button.

00:43:06 - 00:44:03
If you’ve done everything right, the loading completion time should be significantly lower. All right, I’ll give you a couple of seconds here to pause. All right, the key piece of understanding to fixing this problem is of course that loading individual articles is independent of each other. So we can use the async builder function to spawn a bunch of loading processes and then wait for all of their results. As a point to jump off from, I’ll bring in the suspending implementation from

00:43:34 - 00:44:31
our first task right here. Because the body of our function is already wrapped in this coroutine scope builder, we would not actually have to explicitly return, but simply have a last expression of the correct return type. Of course, we still haven’t started any new coroutines here yet, so let’s do that now. Let’s start by identifying which part of the code should be started in each individual coroutine. Well, our map function is pretty much equivalent to a loop, so this is where most of the

00:44:03 - 00:45:02
work gets started. We can simply wrap whatever is in this block in async. Of course, the type of this will be different now because we’ll be working with a bunch of deferreds. So we can have our collection of deferreds here, which is a list of deferreds. Now we just need to wait for all of them, which we can do using the await all function, and we have a solution that type checks again. So let’s see if it actually does what we expected to. I’ll start the articles app again. I’ll make

00:44:33 - 00:45:32
sure that I move to the concurrent loading mode and I’ll hit load comments. And we can now see that we have loaded the same number of articles in just two seconds rather than the 9.1 seconds that it took us beforehand. That’s quite a significant boost for changing just a couple lines of code. Of course, the key insight here comes from figuring out which part of our code we can split up across different coroutines. So the placement of the async builder function is not arbitrary. Had we, for example,

00:45:02 - 00:46:06
moved the async block outside of the map function like this, then we would not have gained anything at all. Why? Because we would have started one new coroutine and this new coroutine would have had to do all of the work of getting all of the comments and creating all of the article objects sequentially. Because within a single coroutine all of your code still runs sequentially. By the way, as someone who loves looking at type hints more than anything else, uh the type hint actually also gives us an

00:45:34 - 00:46:40
indication that this would not be the solution that we want to. Why? Because rather than getting a number of deferreds that we could await individually or as a group, we just get one big deferred of type list article. And that’s really what we want. Let me reconstruct the code that we had previously. Another pattern that you might gravitate towards if you come from a language where async and await are the core primitive with which you work is to, for example, wrap the get comments call uh in async and then call await as part of

00:46:06 - 00:47:03
the uh article constructor. But this too does not provide any benefits. Why? Because this code effectively says start a new coroutine that executes this suspending function and then immediately wait for the result of it. Well, if the next step of our process immediately requires the direct result of the previous line, we could have just used a suspending function in the first place. There is no need to go through the machinery of starting a new coroutine, grabbing a deferred, and then awaiting that

00:46:35 - 00:47:26
deferred. You can simply use a suspending function. So let’s move back to the ideal solution again. Another function that I want to shout out here is the await all function. So rather than creating a loop for the deferreds and then waiting for each one of them one after the other, await all is the preferred solution. For this specific demo case, it wouldn’t make much of a tangible difference, but especially when you think about situations where you might handle errors, this might be quite a

00:47:01 - 00:48:00
difference. Think of the following scenario. You have two coroutines. One coroutine computes for 10 seconds. The other one computes for 100 milliseconds and then it fails. If you were looping over all the defers, there is a scenario where you first wait for 10 seconds, do the entire computation, look at the next deferred and realize that your entire computation doesn’t work anymore. With await all, you get a specialized function where if any of the defers throw an exception, you’ll get that

00:47:30 - 00:48:34
exception back. This isn’t load-bearing information for this specific example code, but I have a hard time holding myself back when it comes to promoting best practices. We have many more subjects ahead of us, but I want to take a brief moment to note a specific interesting design decision about Kotlin coroutines. And that is that most of the API surface that we are using all throughout this course and in general development is actually part of a library. It’s Kotlin X coroutines. The language or the Kotlin compiler

00:48:02 - 00:49:01
itself actually only provides the suspend mechanism. That one is built in. Everything else is abstractions that are built on top of that that don’t necessarily require special compiler support. Interestingly enough, the idea of a function that can pause, of a suspend function, is so powerful that it can be used for things other than concurrency. For example, the next time you are using sequence builders, you might want to see if there isn’t a little suspend icon in the gutter when you are creating new

00:48:32 - 00:49:39
elements as part of your sequence builder. Okay, with that wrapped up, let’s move on to our next major topic, and that’s deciding on which threads your code is actually running, which we do in Kotlin coroutines using dispatchers. Now, remember that coroutines are an abstraction on top of threads. So each coroutine runs on some sort of carrier thread. The key question though, of course, is which thread specifically is your code then running on. And this is exactly what the dispatchers in Kotlin coroutines are

00:49:05 - 00:50:11
for. We’ve caught a very brief glimpse of them earlier when we parameterized an async builder with a dispatcher. But now it’s time to dive a little bit deeper and actually gain a more full understanding of what dispatchers are all about. At its core, the dispatcher that’s associated with a coroutine decides which thread or thread pool that given coroutine runs on. And the dispatcher that you choose actually impacts multiple different aspects of your application. There is performance, of course, but it also

00:49:38 - 00:50:36
involves, for example, the parallelism or you might have external requirements that are imposed upon you from a framework. So what kind of dispatchers are actually available to us? Well, there is dispatchers.default. This one is the default thread pool as its name might suggest. And it’s a thread pool with the same number of threads as the number of cores that are in your machine. This default dispatcher is best used when you have CPU bound work. So when you are just doing some computations.

00:50:07 - 00:51:17
Next, there is the specialized main dispatcher. This one is specifically designed for updating the UI. Because the main thread in UI frameworks take a special role, this dispatcher is actually typically provided by your framework. I also want to note right away that the main dispatcher is not so relevant when you are writing compose UI code because the overall patterns are slightly different. Rather than you updating the UI directly, you update state which then conditionally re-renders your UI. This

00:50:42 - 00:51:54
is just a small side note. Then there’s dispatchers.io, which is specifically designed for blocking tasks. In real applications, the main type of blocking tasks that you will encounter will mainly be IO APIs that are not coroutines aware. That’s also where it gets its name from. The thread pool underpinning the IO dispatcher has up to 64 threads by default. But of course, there are also scenarios where you may want to tweak the behavior of your dispatchers in situations where you have some custom parallelism

00:51:18 - 00:52:20
requirements. For those scenarios, there is the limited parallelism function which you can also use. So, how do we go about picking a dispatcher then? I hope this very simple flowchart will help you in this process. If you specifically require the UI thread, then you should be using the main dispatcher for your coroutine. If you’re using some sort of blocking API that’s not coroutines aware in your coroutine, then you should be using Dispatchers IO. If you have custom parallelism requirement such as needing

00:51:49 - 00:52:55
to specify a cap, a maximum number of a parallel executing coroutines, then you can use the limited parallelism function. In any other case, you are most likely doing the kind of operations that Dispatchers.default is already well suited for. So, with this understanding, we now need to plug those dispatchers in somewhere. The most straightforward way of passing a dispatcher to a coroutine is by parameterizing its builder function. In this example, we have a markdown converter function uh which converts

00:52:22 - 00:53:23
some HTML documents from HTML to markdown. Since this is just regular work, we are not using blocking IO or we’re not requiring things like the main thread. Here we could for example specify that our async coroutine builder should use the default dispatcher. We simply pass it as the context parameter like we’ve seen a little while ago. In the second example, we are reading some bytes from disk, parsing its contents, and then saving it to some sort of database. Especially this aspect of reading some

00:52:53 - 00:53:59
bytes from a file from disk uh using regular JDK functionality, that is a great indicator that we are doing IO operations here. It’s a blocking operation. Therefore, we can parameterize the launch builder using dispatchers.io, and that work will be done using that separate thread pool of up to 64 threads. But beyond parameterizing, for example, async and launch, there is also a specialized with context coroutine builder that you can use. So if you find yourself having a snippet of code that

00:53:26 - 00:54:31
should simply run on a separate thread, for example, you do some sort of computation and then afterwards you want to update the result on the UI, you can use the with context function. In this example, we are launching a new coroutine on the IO dispatcher. So we’re doing some sort of blocking work. In this case, it’s our perform background operation. Once we have the result from that operation, we switch dispatchers using the with context coroutine builder. The associated new coroutine will then run

00:53:59 - 00:55:02
on the main dispatcher. So here we can call a function like update UI safely even if it requires us to run on the main thread. This is the key use of with context, but when you really look at the shape of its API, you might actually recognize an old friend here again because with context in its shape and behavior is actually quite similar to coroutine scope because with context too is a suspend function. If you are making any sort of suspend function invocations as part of the lambda, it will wait for them. Since it

00:54:31 - 00:55:29
is a coroutine builder, it provides you a coroutine scope in the lambda receiver, so you can actually start new coroutines as a child of with context, like launch and async. And it also waits for the completion of all of those child coroutines. With context, just like coroutine scope can also return a value. It is simply another scope function. Its key difference is that it gives you the ability to change the coroutine context and override elements with something else. So now that we have learned the

00:54:59 - 00:56:05
tools that we can use to move work off of one dispatcher and onto another, it’s time to introduce a really important concept that coroutines code has to follow. The general concept is that a suspend function should not block its caller. Hopefully this already matches your intuition about what suspending functions should do. you have a background in Android development, you may have heard the term main safety before. This one describes that a function should be safe to call from the main thread. So it should be

00:55:32 - 00:56:36
able to be executed wherever the UI is rendered many many times a second. If you are calling blocking APIs that occupy the thread when it could be doing other things like rendering the UI, you end up with laggy UI, which is something that is really important to avoid. But this is not an Android specific concept. Generally, suspend functions should be non-blocking for their caller, which leads us to the fundamental rule that you need to internalize here. A general suspend function shouldn’t directly invoke blocking code.

00:56:04 - 00:57:10
This is exactly the kind of problem that is exhibited by this read large file function on here. It calls read bytes, which by default is a blocking API. If the UI thread of my application were to invoke this function, then despite being decorated by a suspend modifier, my UI would freeze. Why? Because the read bytes function simply blocks the underlying thread until all bytes have been read. And I want to note here that if I had picked a more modern API like path or a file channel, this also would

00:56:37 - 00:57:43
not have changed. We need to approach this differently. Here we’re using the with context function parameterized with dispatcher’s IO to move the work of reading the bytes from disk into the IO thread pool. That means whoever has invoked read large file is not being blocked by this operation. This function just suspends. Of course dispatcher’s dot IO is just a Kotlin object. So if you wanted to, you could even parameterize the read large file function and allow people to specify their own custom dispatcher should they

00:57:10 - 00:58:15
so desire. Note by the way that there is a second operation that works with the bytes that with context has returned to us here to for example stored in some side of database. If you are using a library function, it is typically the responsible of that library to hold up their end of the contract. After all, their functions should also be main safe or non-blocking for the caller. That’s why in this example store bytes is not part of the with context invocation but is done afterwards. So we talked about different dispatchers and

00:57:42 - 00:58:40
the different thread pools that they run on. But whenever we find ourselves in a situation where more than one thread is involved, there are a couple of things that we need to keep in mind. Let me show you a code snippet to motivate what I mean. So back over in IntelliJ, here’s what I came up with as a motivating example. I have a variable called X which is initialized to zero. Then I create myself a coroutine scope so I can launch a couple of coroutines and then just start 10,000 coroutines on the

00:58:11 - 00:59:21
default dispatcher that all just increment X by one. After the coroutine scope is all done and dusted and has waited for the completion of all of its children, I then print X. The question now that you can ask yourself is what the result will be. What value will X have after execution? Well, let’s just run it and see. Intuitively you may have said well it should certainly be 10,000 but the actual result is 9,835. So what’s going on here? Well we find ourselves in a situation where we’ve

00:58:46 - 00:59:49
shared mutable state that is being accessed and modified by different threads at the same time. If you recall dispatchers.default is a thread pool with the same number of threads as the number of cores I have in my machine and since I was not using any kind of primitive that is specifically designed to be thread safe, I just have a mutable variable. Well, quite frankly I’m losing a couple of updates here. I also want to briefly note here that I specified dispatchers.default mainly to make it a

00:59:18 - 01:00:17
little bit more obvious, but of course launch would have also used the default dispatcher if there was no other dispatcher specified anywhere in its configuration and we still get a very similar number that’s less than 10,000. Coroutines are great, but they are still a lightweight abstraction on top of threads, which means if you find yourself in a scenario where you working with parallelism where multiple threads are modifying things, then just picking coroutines is not an auto fix for these

00:59:48 - 01:00:50
kind of issues. But thankfully coroutines also don’t require any kind of special treatment. The same approaches that worked with threads also work with coroutines. One example would be atomics. I can use the atomic int from the in standard library. This one is still currently experimental, so we’ll opt into it, but you could also use a JVM only atomic integer would work just the same. And instead of x + + we’ll do an increment and fetch. IntelliJ rightfully now tells me that it is no longer a mutable

01:00:19 - 01:01:24
variable reference, so we can turn this into a val. Rerunning the same code now gives us the flat 10,000 that we expected. Alternatively, we could also reach for other synchronization primitives. So let me just undo this change for a second here. And instead I could for example specify a mutex. This one comes from the coroutines machinery as well. And now I can define a critical section. So for example I can say mutex. with lock which is a fancy extension function which makes sure that I have the lock

01:00:52 - 01:01:59
before I enter my critical section and automatically releases it. With this implementation rerunning it again, we still get the value of 10,000. But rather than using the atomics effectively here we have asked our coroutines to all nicely wait their turn to increment the value so that nothing gets lost. Which primitive specifically you want to choose of course depends on the specific use case. Atomic data types are great for securing individual variables, mutexes are great for securing critical sections and

01:01:25 - 01:02:21
semaphores are great for limiting the number of concurrently running processes. So here you can pick and choose. But of course, if you can rewrite your code in a way that avoids mutable state in the first place, that would be even preferred. It’s not always possible, but when it is possible, it is often really worth it. To show you that this doesn’t just work in a clean room environment, the server that’s integrated with the accompanying project actually also has two interesting endpoints. It has a

01:01:53 - 01:02:56
wallet earn endpoint and a wallet money endpoint. And if we take a look at the implementation, we will see that it suffers from exactly the same problem that we just talked through. We have some shared state. In this case, once again, it is an integer that just lives top level and is a mutable variable that’s not protected to be used in multi-threaded environments at all. Then we have an earn route which just increments the money every time it is called and then we have the money route which just tells us how much money we

01:02:25 - 01:03:34
have in our wallet. We can use a tool like Apache Bench to simulate a large number of concurrent incoming requests and see how our server behaves. Here’s the command for that. It’s just Apache Bench. We want to make 10,000 requests with a concurrency factor of 50. So 50 of those will be started at a time and it will hit the endpoint wallet/earn. Starting this very quickly, it starts and runs through the 10,000 requests. Now let’s take a look at how much money is in our wallet. Well, it’s 9,865.

01:02:59 - 01:04:08
So some of those request updates were straight up lost. Of course, by now in hindsight, this shouldn’t really be surprising to us anymore. Ktor runs the request handlers on a multi-threaded dispatcher. So if we have any kind of state that is shared between those, we need to make sure that it is well equipped to exist in a concurrent environment. Again, exchanging our definition with, for example, an atomic int, then re-running our server, re-running our benchmark, and then checking the value of course

01:03:34 - 01:04:30
fixes it. The important nuance here is of course that whenever we talk about shared state, we mean shared between multiple coroutines. If you have the question, can I use a mutable map in my coroutine cuz it’s a mutable object? Yes, you can as long as it stays constrained within a single coroutine. All your visibility guarantees apply. Any modifications that you make first will be visible in the code that’s below it. However, when there is more than one coroutine that can access your map,

01:04:02 - 01:04:57
that’s when you need to be more careful and use, for example, a mutex. This is also one of the confusions that we frequently see when people are using the limited parallelism function. So I think it’s important we take a couple of minutes here and talk about what it really does. The limited parallelism function allows you to take an existing dispatcher like dispatchers.default or dispatchers.io and it then allows you to specify an upper limit on the number of threads that a thread pool can use for that

01:04:30 - 01:05:39
specific dispatcher. The important part is that limited parallelism is a view on an existing dispatcher. Take for example the io dispatcher which starts with 64 threads by default. If you were to parameterize this io dispatcher with limited parallelism of four, then the newly created dispatcher would use four of those 64 threads. Though which ones exactly can still change at runtime. Most importantly, this dispatcher is not designed to replace any of the synchronization primitives that we have in calling coroutines. We sometimes see

01:05:05 - 01:06:08
people write code like this, for example, where they specify a dispatcher with limited parallelism of two in the hopes that when their operation get info starts 64 operations that only two of them will happen at the same time. However, it is important to keep in mind that limited parallelism is only about the number of carrier threads that are used at the same time, and it does not impose any kind of limit on the number of concurrently running coroutines. In other words, even in this scenario, you will have 64 coroutines starting and

01:05:36 - 01:06:45
getting to work immediately. As such, the limited parallelism function cannot be used as a replacement for, for example, semaphore. In this example, we create a semaphore with two permits. The code inside launch then acquires one of the permits and does the work. In this scenario, all 64 coroutines still start immediately, but they also immediately suspend until they can get one of those permits. And likewise, you can also not use limited parallelism with one as a replacement for a mutex. Why? Because with a mutex, you are

01:06:11 - 01:07:13
typically expecting some sort of critical section behavior, things that you want to be executed without being intertwined in any manner. While the invocation of limited parallelism still limits the number of carrier threads active at the same time, they don’t protect against behavior where different parts of your code would interleave. The coroutines may still switch between those different operations. Once again, the correct solution is to simply reach for a synchronization primitive. Here, picking a mutex gets you exactly

01:06:42 - 01:07:33
the behavior that’s typically intended. Hopefully, these kind of caveats have made it clear why we’ve moved the discussion of limited parallelism out of the general discussion of dispatchers and here when talking about visibility guarantees. At this point, we are almost ready to switch our focus to one of the really cool things that coroutines have to offer, which is structured concurrency. So it’s a good point to take a second again and talk about what we’ve seen so far. Right in the

01:07:08 - 01:08:04
beginning, we understood that the coroutines share many properties with threads, but they are a lightweight abstraction on top of them. You can use them for both concurrent and parallel programming, and they still keep your code clear and simple. The core primitive that we’ve seen is the suspend function. We’ve also seen that even our entry points can be suspend. The coroutine builders that we’ve been exposed to, coroutine scope, launch, async with context, they all start new coroutines. We’ve seen that

01:07:35 - 01:08:37
the job object, sometimes directly, sometimes in the form of a deferred, gives us a handle on coroutines. And we’ve also seen that dispatchers control where your code is executed. They can be used with general purpose builders like launch and async or specialized ones like with context. With dispatchers specifying what underlying threads are actually used to execute your code, we understood a few core concepts. Suspend functions should stay non-blocking for whoever calls them, for example. When you have long blocking

01:08:07 - 01:08:57
work that you need to do in the context of a suspend function, you should move it explicitly to a specialized dispatcher. And of course, let the caller provide the dispatcher. Whenever we encounter shared mutable state, so that is state that is shared across multiple coroutines, that requires extra care. We have multiplatform atomics as part of the Kotlin standard library, and we also have synchronization primitives like mutex or semaphore to protect your critical sections or to limit concurrent

01:08:32 - 01:09:31
execution. And with that, we are ready to tackle our next big topic, structured concurrency. Structured concurrency is one of the key abstractions that we have in Kotlin coroutines, and it is one that matters quite a lot. Why? Because it introduces the parent-child relationship between different coroutines. As such, it affects a number of aspects of how your coroutines behave. For example, it is responsible for the inheritance of context such as the dispatcher that we’ve already seen prior.

01:09:01 - 01:10:01
But it also affects aspects of cancellation, error propagation, and how errors are handled in a system where multiple coroutines are working together. The key motivation why structured concurrency is such an integral part of the Kotlin coroutines library is because it allows you to build reliable concurrent systems. By relying on structured concurrency, you can prevent your system from doing unnecessary work, for example. It helps you avoiding memory or resource leaks in context where things go wrong. And it

01:09:31 - 01:10:31
also in general helps your application stay responsive. I want to show you a couple of motivating examples that will hopefully illustrate why error handling and cancellation is really important if you want to build reliable applications. Let’s start with this hypothetical scenario. Here we have a small application that compiles some sort of business report. This business report is relatively complex to aggregate and it involves a number of different tasks that all need to be executed. For example, you might have some local data

01:10:01 - 01:10:52
that influences the outcomes of the result. For that, you need to obtain a mutex to enter a critical section. You need to validate some inputs which come from a specialized rule set. You need to read some data from disk and all of this comes together as the part of gathering local data. In addition to this, you also need to include some sort of remote data. For example, some monthly statements which you need to retrieve from a bank, from a broker, but also from an insurance and maybe from a tax

01:10:27 - 01:11:23
agency. So the application is clearly doing a lot of things and like the remaining time indicator here shows, uh it’s going to take a couple of minutes to actually create this report. But what if the user is no longer interested in the actual outcome of the report? You really want to avoid doing another seven and a half minutes of work. If this entire operation is running on a mobile device, well, you certainly have a responsibility to save the user’s battery life here. But looking closely

01:10:55 - 01:11:49
at this, we also notice that we have a hierarchy of tasks that are happening here. We are compiling a report which requires us to gather local data and gather remote data. And then for each of those, there are other subtasks that need to be done in order to finish gathering local and remote data. In other words, there is some sort of tree structure of work that needs to be done. And having the individual concurrent processes that are working together to compile this report somehow connected to each other would

01:11:22 - 01:12:27
help us easily make sure that as the user navigates away, no unnecessary work continues to happen. Likewise, we could also very easily think of a situation where something goes wrong. Let’s say, for example, the brokerage API is down. Now the key question really is, now what? Is it even still possible for a full report to be compiled if not all data is available? Wouldn’t it in this case make more sense to propagate this exception across the hierarchy of processes that we have and cancel all of

01:11:54 - 01:12:45
the related works because no meaningful result can be computed anyway? As you can probably tell by my intonation, structure concurrency is going to help us with exactly these kind of things. Let’s consider another case where we have some server-side application which uses a constrained resource like database connections to serve a number of users. If there are some users that are no longer interested in the result of a database query, for example, or simply disconnect, then you need to have

01:12:20 - 01:13:16
a mechanism that allows you to free those database connections and serve other users instead. In short, if you are working with some sort of constrained resource, then you need a way to free those in order to allocate them efficiently. And ideally, this work shouldn’t fall on you as the developer doing some manual handling of these processes, but instead it should be baked right into the concurrency framework. So let’s take a closer look at how you are using structure concurrency in Kotlin coroutines and

01:12:48 - 01:13:46
also how it’s implemented under the hood. To dive into all of this, we’re going to use a fact that we’ve already seen come up a couple of times, and that is that there are coroutine builders like async and launch, which are extensions on coroutine scope. This design decision, the fact that async and launch can only be called whenever you are already in the context of a coroutine scope, actually naturally brings you to using structured concurrency. Because since whenever you invoke launch or async, you

01:13:16 - 01:14:25
invoke it on its parent coroutine scope, you are starting to build up a tree of coroutines. Consider the code on the right here. Going from top to bottom, we have the coroutine scope function invocation which gives us our first coroutine A. Then we launch the next coroutine, which is coroutine B. Note that our invocation of launch was actually using the receiver type coroutine scope from our outer coroutine. This naturally makes the coroutine B a child of coroutine A. You can probably infer what happens next.

01:13:51 - 01:14:54
When we launch another coroutine on coroutine B, it itself becomes a child of coroutine B. That’s what we see here with C. Going further down the hierarchy, we have the launch of coroutine D, which happens as a direct child again of our outer coroutine A. And if we start another coroutine, even using async, that’s our coroutine E inside the launch of D, then it naturally registers again as a child. So even though we have launched five separate coroutines here, they are all grouped together. They form

01:14:22 - 01:15:20
a hierarchy with our coroutine A at the top. But how does this actually work under the hood? Well, let’s take a bit of an X-ray into this hierarchy and see how this is implemented. Here is a view that shows you what’s actually going on under the hood. As you can see, structure concurrency involves coroutine scopes, coroutine contexts, jobs, and references to other coroutines. The coroutine scope, which we’ve also seen plenty of times in code now, is the shell for representing a coroutine in

01:14:52 - 01:15:56
user code. The coroutine context, whose mechanics we’ll dive into a little bit more deeply later on, is responsible for holding a number of special values that are related to the execution of the coroutine. For the topic of structure concurrency, the most important part of the coroutine context is indeed its job because it is responsible for establishing the parent-child relationships between the different coroutines. As we can see from this picture, each coroutine has its own job associated with it, and this job is a

01:15:23 - 01:16:24
part of the coroutine context. In fact, this is the very same job that you have met before when we were talking about launch and async. In both cases, you get a reference to the job object that is stored in the coroutine context. And as you can see, indicated by the arrows, the job is responsible for actually keeping track of the relationship between different types of coroutines. Quite literally, it stores a sequence of child jobs and also can have zero or one parent. You can probably think of

01:15:54 - 01:16:55
another data structure that kind of has the same shape where one object can have multiple children, but each of the children can only have one parent. Indeed, whenever we work with structured concurrency, our coroutine hierarchy forms a tree. So in a way, when we say structured concurrency, you might also say that we are indeed doing tree-structured concurrency. By wiring these jobs together, we get a hierarchical grouping of related computations with their own subtrees. And by sharing a common parent

01:16:24 - 01:17:21
coroutine, we get a central handle that allows us to manage these entire subtrees. This relates to the automatic propagation of cancellation with children being canceled recursively and the automatic propagation of exceptions. This automatic propagation is extremely useful. Consider the following. We are no longer interested in the results of job A. Well, most likely jobs B, C, D, and E will also no longer be useful to us. As such, the coroutine’s machinery will simply automatically cancel their

01:16:53 - 01:17:44
execution by default as well. I wanted to show you this X-ray view before we dive into some code so that you have a mental model of what exactly it is that happens. But let’s see some of this in action as well. Back over here in IntelliJ, let’s build our own small coroutine hierarchy and play around with it for a little bit. Let me first use the lexically scoped builder coroutine scope to get our first coroutine out here. Then let me spawn a couple of jobs in a hierarchy so that we can see that

01:17:19 - 01:18:27
we can easily cancel all of them together. We’ll create a parent job that I’ll hold on to, which will just be a launched coroutine. And inside, we’ll create a couple of additional coroutines that are children of that parent. So we’ll say child one starts. It should delay for a while. Let me say child one completes. We’ll do the same for a second job as well. And maybe we’ll make it a little bit longer. Let’s say two seconds. If you’re on this so far, we shouldn’t see anything

01:17:54 - 01:18:52
surprising. We need to get our parents starting, our child one and child two starting, and then them completing after a short period of time. But let’s say that halfway through the calculation, we’re actually not interested in any of these things that are maybe being computed by our parent job. Let’s model this and let’s say that after 500 milliseconds, I am no longer interested in the result. I don’t care anymore. And here we will simply cancel the parent job. With our understanding now of structured

01:18:23 - 01:19:24
concurrency, we probably have an intuition of what should be printed here. And indeed, we see that the parent starts, the first and second child coroutine start, and then we just see our message of I don’t care anymore. And all coroutines that were part of this parent job, including all of its children, were canceled. So we can see that by having the child coroutines be registered as children of our parent coroutine, we have a single handle that allows us to tear down an entire tree of coroutines. And of course, we could make

01:18:54 - 01:19:52
this arbitrarily deep. So if I were to start a couple of additional coroutines nested more deeply inside each other, no surprising behavior occurs. These are all still canceled together because they are all grouped under one common parent. Let me undo that for a second. While we are already in the IDE, I can also show you what happens when we intentionally break structured concurrency. Instead of starting these coroutines as children of the parent, I could use something like global scope to start these functions

01:19:22 - 01:20:24
just somewhere without a parent. You can see that IntelliJ already starts yelling at me here, warning me that global scope is a delicate API. And for good reason, let me put a small delay in here so that our program doesn’t end immediately. We can see the following. Despite our coroutines being canceled, and we see the I don’t care anymore printed here, child one and child two still completes. Why? Because by using global scope, we’ve made the very bad decision of circumventing structured concurrency.

01:19:53 - 01:20:56
Our our two child coroutines no longer have a parent coroutine. So the cancellation cannot be propagated to them. And this is precisely also the problem why I had to add a delay of 5 seconds here, because even our outermost coroutine scope function, the one that we know waits for all of its child coroutines, no longer has any kind of indirect handle on these coroutines. We started something and they’re just kind of floating in the ether. I hope you can see how in production systems that is something that you really want to avoid.

01:20:25 - 01:21:24
So let me quickly undo this very bad decision. And let’s use this opportunity to show you one more aspect of structured concurrency. Specifically, I’m talking about the inheritance relationships with regards to the coroutine context here. You have already seen that coroutine builder functions like launch and async can be parameterized with a coroutine context. And besides job, which you’ve seen on our X ray slides just a little bit earlier, you also know at least two other types of coroutine context

01:20:54 - 01:22:01
elements by now. It’s the coroutine name and the dispatcher. The coroutine context also participates in structured concurrency. When we start new child coroutines, they inherit the context of their parent and have the ability to override some of the elements from what they have inherited. Let me demonstrate how things are inherited in a somewhat visual way. Let me just specify a coroutine name for our parent coroutine. And we will call this just my workload. Running this, we can see that indeed the parent coroutine that we

01:21:27 - 01:22:33
have here now indeed identifies itself as my workload in the logs. Likewise, this coroutine name context element is also propagated down to our children. We can see this down here in the logs where child starts and child two starts. They identify themselves as my workload coroutine two and three. And and this should intuitively make sense because they are grouped together. They are computations that belong together to a common parent. But of course, coroutines can still override some of these elements. For example, I might specify a

01:22:00 - 01:23:07
separate coroutine name for my first child and we’ll call this one first child. Now we can see that indeed the first child identifies itself as such, while the second child still continues simply inheriting the my workload name from its parent. And of course, we aren’t limited to the coroutine name here. For example, I could specify dispatchers.io for our parent coroutine and use the plus operator to combine it into the new context that I want to pass to this launch builder function. Unfortunately,

01:22:34 - 01:23:41
this change isn’t quite as visible because both IO and the default dispatcher share some threads as a performance optimization. So you could of course just take my word for this, but I could also show you that it is indeed inherited. Let me use the current coroutine context function and simply log that one for our C one. Indeed, we can see that the C one coroutine context, the one from our first child, includes dispatchers.io as part of its coroutine context. And indeed, we can see all of the other

01:23:07 - 01:24:00
coroutine context elements here as well, the first child coroutine name for example. Here we also see an ID and we can also see the job that is associated with this specific coroutine. In this case, it’s called standalone coroutine, but it is a job. In the parentheses here, you can also see that this job is active. So with this, we now have a little bit of practical experience under the belt of how structure concurrency works in Kotlin. As we’ve seen in this demo and on the slides before, the

01:23:33 - 01:24:26
coroutine scope is one of the key points that allows you to create new coroutines that are registered with their parent forming this parent and child hierarchy. And there are a number of ways of how such a coroutine scope instance can be obtained. If your code runs in the context of an overarching framework, like you’re building an Android application or a Ktor application, those systems already provide some coroutine scopes for you to start coroutines on, and they naturally connect the lifetime

01:24:00 - 01:24:56
of your coroutines to some semantics of the overarching system. Of course, we have also seen that coroutine builder functions, since they create a new coroutine, always give you a new coroutine scope. This includes those coroutine builders that are themselves extensions on coroutine scope. They still create their own new coroutine with its associated coroutine scope, but it also includes our old friends, the lowercase C coroutine scope, lexical coroutine builder, and the with context function. And of course, for those, you

01:24:28 - 01:25:25
don’t need to be in a coroutine scope environment already. Indeed, the special run blocking function also gives you a coroutine scope available for you to start new coroutines on as well. But since the coroutine scope is just a regular Kotlin interface, there are a few other ways of how you can also obtain it. For example, you can have a function that takes a coroutine scope as a parameter, either explicitly or as a receiver type, making it an extension on coroutine scope, which semantically

01:24:56 - 01:25:53
means that this function spawns coroutines on a provided coroutine scope from somewhere else. And for the more narrow case of constructing components that need to manage their own life cycle, there is also the capital C coroutine scope constructor function. All of these points deserve a little bit more attention, so let’s take a closer look at some of them. Starting with the framework story. If you are working on Android and you’re building some code that works in a view model, for example,

01:25:25 - 01:26:25
well, you get a view model scope associated with that out of the box. If you’re using Ktor, there’s actually multiple different scopes that you can choose from. There is an application scope which lives as long as the entire application, so you can just call application.launch. And there is also scopes that are scoped to the lifetime of an individual call or an individual request handler. Here you would simply call call.launch. Considering the Android case, for example, here I have my own view model

01:25:55 - 01:27:03
which just inherits from the Android X lifecycle view model. Now I can create a function called do thing and in here I can see that I do indeed have access to a view model scope property. So I can, for example, launch a new coroutine on this view model scope. This is the first time throughout this course where we have seen the launch coroutine builder being explicitly invoked on a scope. Beforehand, we were always using the this reference that was provided to us in context. But from my many repetitions, we recall that launch is

01:26:29 - 01:27:30
simply an extension function on coroutine scope. So as long as we have an object that is a coroutine scope, like we do here with view model scope, we can call builders like launch and async. And with some intuition, you might also be able to infer the lifetime of this view model scope. Indeed, when the clear function of the view model is invoked, this view model scope is also cancelled. So when the view model is no longer needed by the surrounding system, then any work that you’re doing in coroutines is also automatically

01:27:00 - 01:28:02
stopped. Moving over to a Ktor example, we could, for example, start a new coroutine which shares the lifetime of the request handler. So this call.launch, whatever we will do in here, will live for as long as the request handler itself lives. It also means that, for example, if this request handler cancels for whatever reason, that our work here is also cancelled. If you want to do some long-running work that should complete regardless of whether the individual request handler is cancelled, you can instead use the

01:27:31 - 01:28:30
application object, which also implements coroutine scope and use it to launch a new coroutine. This coroutine will continue running even if the request handler is cancelled, for example. And in the case of Ktor, this is actually a key decision of how you want to structure your application code. If you have some long running computation, whose result you’ll store in a database at the end of it, and you don’t really care whether the user is still around to actually receive the result, then you should probably start

01:28:00 - 01:29:07
it on the application scope. But if you are doing some intense work with the sole intention of returning a result to the user, then that work should probably be canceled if the request handler itself is also canceled. So depending on what you’re doing, you would choose a different scope to launch your workload on. Now there are also scenarios where you may be writing code whose sole responsibility it is to start a new coroutine on a provided parameter coroutine scope. Here what your code effectively does is

01:28:34 - 01:29:37
that it starts new coroutines that are tied to the life cycle of whoever is calling this code. This of course influences topics like cancellation. If you are writing a function that allows the caller to create a new coroutine, then that newly created coroutine is practically the responsibility of the caller. It will become a new child in the parent child hierarchy of the caller. And of course the exception handling story is no different here. Whoever is then owning this coroutine is responsible for how exceptions are

01:29:05 - 01:30:12
handled. As such, this is typically reserved for what I would call setup code. It effectively allows you to create your own coroutine builders. Let me show you an example use case that illustrates taking a coroutine scope as a parameter. In this in this code example, we launch a new coroutine which just loops and merges some data from a remote service over and over again. What if we wanted to extract the creation of this coroutine into a separate function? Well, we could approach this the following way. I can simply take this

01:29:38 - 01:30:44
function and I can extract it into a new function. Let’s So let’s take a look at how IntelliJ extracted this function. This new launch sync engine function needs to have a coroutine scope as a receiver type. We could rewrite this code a little bit to make this even more clear. Specifically, we could launch the coroutine on this because this is the receiver type that we get from coroutine scope. Alternatively, to make this even more explicit, we could also turn this receiver type into a parameter calling

01:30:12 - 01:31:17
it scope. And we can see how the call site also changes. So now we would have a function that explicitly takes a scope parameter, and the code inside of our launch sync engine function launches a new coroutine on that scope. We can see that even with this code transformation, it is still the responsibility of our outer coroutine scope function that we have here to wait for whatever has been created by launch sync engine. So this is precisely one of the key use cases where you can accept a coroutine scope

01:30:43 - 01:31:47
as a parameter either directly or as a receiver type. Before leaving this example, I do want to point out one specific thing about this launch sync engine function though that is important to understand. This function is not a suspending function. Why? Well, because its entire job is to only start a new coroutine on a provided coroutine scope. No suspending work takes place when we call launch sync engine. All the suspending work happens inside of that coroutine that is created on this provided coroutine scope. This function

01:31:17 - 01:32:11
just creates the new coroutine and returns effectively immediately. We have already spent a significant amount of time exposed to the lowercase c coroutine scope coroutine builder function, the lexically scoped coroutine builder. So I don’t want to spend too much time talking about it here again. This is mainly here for your reference once more. The most important part that I want to shout out again is that the coroutine scope builder is used for the concurrent decomposition of work. So you

01:31:44 - 01:32:45
can use it to compute a bunch of different things in different coroutines. You can wait for their completion and then they return a result. Effectively, this allows you to package a number of coroutines into a suspend function. And that’s precisely what you can see right here, where our calculate total function simply returns whatever the coroutine scope function here returns, which in turn internally uses get numbers low a couple of times and then creates some sort of joint value. By now you’ve probably noticed that I

01:32:14 - 01:33:17
try as much as possible to be very precise when I talk about these coroutine scope related subjects. The core problem that I am trying to navigate around here is one of naming. It’s the fact that we have something called coroutine scope with a lowercase c, which is our coroutine builder, but we also have the capital C coroutine scope interface. Now when it’s written out on the slide, you can tell the difference quite clearly, but when I’m talking about it, this is why I always try to provide you with the

01:32:46 - 01:33:55
suffix of coroutine scope builder function or the coroutine scope interface. So I do have a bit of a personal case here, which is that I think this function, the builder, should actually be called coroutine scoped. And I think that looking at my argument will at the very least help you make this distinction a little bit easier. You see, in Kotlin Native we have another function called mem scoped and its main purpose is that if you’re writing code in an environment where you don’t have a garbage collector, you

01:33:20 - 01:34:26
still want to be sure that once your code has finished, that everything you have allocated memory wise is also freed again. So fundamentally here we are already looking at a very similar pattern. It’s lexical scoping, but this time it is for memory. And probably looking at this code snippet, you can already tell that there’s a couple of similarities between this and the coroutine scope function. Mem scoped provides you with a mem scope as the receiver type as the this for the block that follows. Functions like alloc array

01:33:53 - 01:35:02
are an extension on mem scope, just like launch is an extension on coroutine scope. So in a part of Kotlin far, far away from coroutines, we have a setup where we have a mem scope which gets a function called mem scoped to create one of them. And in coroutines we have our coroutine scope which has the function coroutine scope without the D. So if you in your mind need a slightly different way of holding on to the difference between coroutine scope and coroutine scope, maybe it is helpful to think of one of

01:34:28 - 01:35:23
them as coroutine scoped. We’ve seen the coroutine scoped builder function a couple of times in action already, so this code snippet should not really surprise you anymore, but I did want to spend a little bit of time putting it in relation with the structure concurrency subject that we’ve talked about beforehand. Fundamentally the coroutine scope function does exactly the same. As we start new coroutines to compute some sort of number, we create new coroutine scopes which have their own coroutine

01:34:55 - 01:35:53
context, which have their own jobs. Upon creation those jobs are wired up to the parent job. In our case that is the job that is associated with the coroutine scope builder. And the fact that you have this kind of hierarchy is exactly also how coroutine scope knows to wait for its child coroutines. With that let’s move on on our journey on how we can actually obtain a coroutine scope instance because there is one more way that you will most likely encounter out in the wild and that is the invocation

01:35:25 - 01:36:29
of the coroutine scope constructor function. This one is specifically designed for associating coroutines with the lifetime or life cycle of a component. This of course implies that the component has some sort of external life cycle management that surrounds it. You can see an example of what such a component might look like on the screen right here. Here we simply define a thing with its own lifetime which also wants to be able to start some coroutines. Of course those coroutines should be tied to the lifetime of that

01:35:56 - 01:36:53
very thing. And And see all key elements of this pattern right here on the screen. First, to make sure that in tests, the coroutine scope can be overridden, we will take an optional constructor parameter. Then we create our own scope using the coroutine scope constructor function. And here we provide the job object that will quite literally be responsible for managing the parent and child hierarchies. Later on, as we talk about error handling, we’ll also see a different type of job, the supervisor job, which

01:36:25 - 01:37:35
is also commonly placed right here. By looking at this code, you can probably already tell that the scope that is associated with our thing does not have another parent coroutine. So effectively here we have created a root scope. With these types of root scopes, it is our responsibility as a developer to make sure that they are canceled when the lifetime of our object ends. In our example that we see here, we can see that our thing implements auto closable and that the close function actually calls scope.cancel. This is our way of

01:37:00 - 01:38:05
manually making sure that any work that was started on this coroutine scope will be canceled when the close function of our thing is called. And the fact that this coroutine scope does not have any further parents is an important one to remember because such structures act as the roots of trees from the perspective of structure concurrency in your application. These are typically tied into some sort of overarching lifecycle manager. In the Android example, the Android framework takes care of the lifecycle of view

01:37:33 - 01:38:36
models, for example. But it is important to note that you might find yourself in a situation where your entire system is comprised of more than one such tree structure hierarchies. And especially because it may be tempting to create such root scopes whatever you see fit, it is important to treat multiple hierarchies in your application as a special case. The general rule of thumb is that the more coherent you can make your hierarchy of coroutines, the easier it will be to manage your entire system. Of course,

01:38:05 - 01:39:04
there are situations where having multiple hierarchies is unavoidable. For example, your system or framework might be imposing these limitations on you. We already briefly discussed one of the prime examples of exactly this case, which are Android view models. Here, the life cycle of a view model is managed externally. So there is a view model store owner that takes care of this. And the clear function is being called explicitly, which then cancels the associated scope. But if you find yourself in an application where you

01:38:34 - 01:39:29
don’t have such pre-existing requirements, where you have full control over the application architecture, you should aim to create a unified hierarchy of your coroutines. Because connecting together these different types of hierarchies allows you to have a unified way of, for example, canceling work. The good news is that even if you’re using this coroutine scope constructor function to create scopes that are associated with your components, you can still make use of structure concurrency. Rather than

01:39:01 - 01:40:02
taking a test scope as a parameter to your component, you can instead pass a parent scope to the constructor. And then you can explicitly wire up the parent scope’s coroutine context and add a new job that is wired up to the parent job. This way, if the parent scope of your component is ever canceled, you can be sure that any work that is happening as part of the coroutines associated with your component scope will also be canceled. I think it is important to acknowledge here that the code that I’m

01:39:32 - 01:40:31
showing you here doesn’t look particularly nice or concise. Quite frankly, here we are looking at a limitation of the current coroutines API. We hope that in the future we’ll be able to provide APIs that make creating such scopes easier. In the meantime, I would still encourage you to do whatever you can to manage as few disparate coroutine hierarchies as possible. Before wrapping up with this section, let me take a brief moment to yell at global scope once more. Recall that like we saw in the live demo, global scope

01:40:01 - 01:41:01
allows you to start your coroutines without actually attaching them to any scope in your application. Hopefully, your intuition also tells you that that’s a pretty bad idea. Consider the following case where we are using the coroutine scope builder function and then creating a couple of coroutines, but we are doing so using global scope. So they are in no way connected to our original coroutine that we created. So what we end up with is, well, there is a hierarchy from those first two coroutines, and there’s one coroutine

01:40:32 - 01:41:25
that just doesn’t have a parent, doesn’t have a child, and is just kind of floating in the ether with our original coroutine having no handle on either of them. So as an escape hatch, global scope makes you ignore the structure concurrency machinery, but it also means that you ignore a lot of the benefits that you get there. Cancellation, resource leak prevention, lifecycle awareness, all of these kind of things. That’s why your code lights up in yellow with a warning, and you will be told

01:40:58 - 01:41:54
that it’s a delicate API that requires specific care. My general recommendation is to simply not use it. In most, if not all cases, you can typically find a better scope to work with. But it does bring up the question of why global scope exists in the first place then. And the answer for this is twofold. On the one hand, there are historical reasons. When work was started on Kotlinx coroutines, structure concurrency was not a part of the framework. It only got added in a slightly later version. Here, global

01:41:25 - 01:42:28
scope was introduced as an escape hatch for people to easily migrate their code to newer versions without having to go all in on structure concurrency right away. But it has been a long time since 0.26.0. And there are those really rare cases where you know that you need a coroutine whose lifetime is equivalent to the lifetime of the entire application. But even then, since you already know how to create root scopes, it is probably a better idea to do that than to simply rely on global scope. Structure

01:41:57 - 01:42:56
concurrency can unfold its full potential the fewer separate hierarchies of coroutines you have in your application. Because as you strive to make the different concurrent processes in your application more interconnected, you get a better handle on the different parts of your application. As such, general advice on how to structure your applications would be ideally to use suspending functions and lexical coroutine scopes because these are generally quite easy to reason about and they are also very usefully constrained.

01:42:27 - 01:43:17
You know that when the coroutine scope function returns that all the coroutines inside of it have finished. When you need to build these types of component structures that we’ve seen on the slides before, then it is still a decent choice if your architecture allows, if you can connect them with some parent coroutines. A reminder that you do that by passing in the job to the job constructor of your component, which as we’ve seen before is done by manually wiring up parent-child relationships. If

01:42:52 - 01:43:45
you are constrained or have a requirement from your architecture to have your component’s lifecycle or lifetime be managed externally, then you can do that as well integrating with the explicit cancel option that we’ve seen. The part that should be avoided are any kinds of tricks or approaches that gets you around using structured concurrency paradigms, whether that’s global scope or some other flavors. Of course, concurrent systems have been built for a long time and many people have thought

01:43:18 - 01:44:13
about the concepts of cancellation and error handling. If you want to get a deeper understanding of what the absence of structure concurrency means for programming languages that support concurrent paradigms, I encourage you to check out the blog post that we have linked here before. During the implementation of structure concurrency inside of Kotlin coroutines, this blog post has actually been a pretty big inspiration for the team. By now, we have seen an overview of the mechanics of structure concurrency in Kotlin

01:43:46 - 01:44:43
coroutines. Next, let’s talk about an aspect that we’ve already seen here and there, but that deserves proper attention. Coroutine context. A somewhat formal definition of the role that coroutine context plays would be to say that it is an immutable set of elements that dictates how your code is executed. Though you can effectively just think of it as a bag of special values that are associated with each individual coroutine. Though I want you to pay attention to the word immutable, the set of elements

01:44:14 - 01:45:07
in a coroutine context for a given coroutine does not change once it has been created. So what kind of special values do we typically encounter in a coroutine context? Well, we have already seen a couple of those throughout the demos and slides. There is, of course, the coroutine dispatcher, which decides the question of threading, of where your code and your coroutine will actually run. Then there is the job, which, as we know, participates in parent-child relationship management. It is also your

01:44:41 - 01:45:39
handle for canceling entire subtrees of coroutines, and it also participates in exception handling, as we will see later. And then there is additional attached metadata, like the coroutine name that we’ve already seen before, and the coroutine exception handler, which we will cover in much more detail a little bit later. Libraries may also sometimes add specialized custom context elements, such as the MDC, the map diagnostic context that you might see in Ktor. Though it is important to note that the

01:45:10 - 01:46:14
contents of the coroutine context are generally constrained for special values that are associated with the coroutine’s machinery. So you’re generally discouraged from trying to put arbitrary values into the coroutine context. Coroutine contexts are the key part of the inheritance part of structure concurrency. They are passed down the hierarchy. Generally, when you create a new child coroutine on a parent coroutine, it inherits that parent context. By by adding arguments to the coroutine builder invocations, you can

01:45:42 - 01:46:51
override or add elements to that coroutine context. And then since every coroutine has its own unique job associated with it, the coroutine builder then creates a new job for this coroutine, and that job becomes a child of the parent’s coroutine job. That means that for a given coroutine, its context is the parent context plus whatever parameters you provided, which potentially override the elements from the parent context. Remember here that the coroutine context has set semantics. That means that only one of each kind

01:46:16 - 01:47:11
can exist inside the coroutine context. For example, providing a dispatcher as a parameter would override the existing dispatcher that would otherwise have been inherited. And then it gets its own job that becomes the child of the parent job. We can map this out by actually just taking a look at what the coroutine context looks like at each step of this program. It is very simple. We just start in a suspending main entry point. We switch dispatchers using with context and we start two coroutines, one

01:46:44 - 01:47:49
unparameterized and one specifying a dispatcher and a coroutine name. Our journey begins in the main entry point with an empty coroutine context. Next, we use the with context coroutine builder that is parameterized with dispatchers.default. We didn’t really have anything to inherit just yet, so all that happens is that we apply our parameters, we add dispatchers.default, and we create a job for ourselves. When we next invoke launch inside of our call to with context, we inherit the dispatchers.default coroutine context

01:47:16 - 01:48:19
element and we create our own new job object for this coroutine, wiring it up with the parent job. So immediately the parent-child relationship is established. Let’s next construct the coroutine context of our new coroutine that uses dispatchers.io and specifies a coroutine name. As a first step, we would of course inherit dispatchers.default. However, we have a parameter that specifies a different type of dispatcher that overrides it. That means the coroutine context used by our latest coroutine uses dispatchers.io. It

01:47:48 - 01:48:48
creates its own job, which is once again wired up to the parent, and there is an additional And since we also added the coroutine name context element, that one is now also part of the context. Looking at this, you can clearly see that out of the box a coroutine just inherits the coroutine context from its parent and adds its own new job. It is the parameterization of the builder functions that allow us to make changes. So we We these concepts on the slides, but let’s also see them in real code for

01:48:18 - 01:49:19
just a second. Here I’m just in my suspend fun main entry point and to see what the current coroutine context is, I can actually call a special function called current coroutine context. This one is available whenever I am in a suspending function. Running this code will show us that we do indeed start with an empty coroutine context, a context that doesn’t have any elements in it. This should intuitively also make sense because we haven’t started any coroutines yet and only when we start a

01:48:49 - 01:49:49
coroutine do we start seeing things like jobs and so on. So let’s do exactly that and use the coroutine scope builder function and let’s take a look at the coroutine context in here. And indeed we no longer have an empty coroutine context. Instead we have a coroutine context that contains a job. It’s called scope coroutine, but that’s our job. If we had chosen a different builder like for example with context and would have specified dispatchers.io, we can see that now our second

01:49:19 - 01:50:23
invocation of current coroutine context does give us the dispatched coroutine. That’s once again our job and dispatchers.io. So indeed we used parameterization to add an element to our coroutine context. Likewise if you use coroutine scope together with the launch function, we might specify the dispatcher in here, parameterizing it and by printing its context we once again see that we do indeed get the dispatcher, we get the coroutine and this case we also get a coroutine ID. This part is courtesy of

01:49:51 - 01:50:52
the Kotlinx coroutines debug flag. Like we have seen prior, if I were to nest a couple of launches, these would of course all still inherit information from their parents, meaning that even coroutine number four still uses dispatchers.io. But once again while we are already here, we can also briefly explore the relationship between coroutines in their parent and child relationship. Here I’m starting a new coroutine and delaying for a couple milliseconds. Conceptually by now we know that this is

01:50:22 - 01:51:28
a child coroutine of our outer coroutine scope builder, but can we see where this exactly happens? The answer is yes, because we can actually take a look and see whether this newly created job is a part of the children of our current coroutine context. So we can do exactly that. What we really want to check is whether the job is present in our current coroutines contexts jobs children list. And if we run this, we indeed see true. We could also just get a list view of all of the children which only has a

01:50:55 - 01:51:58
single element. So once again we can see that mechanically things are wired together using the jobs. But we can use the opportunity of being in the IDE here already to solve one more small mystery. We’ve seen that generally when we launch a new coroutine it inherits the dispatcher for example from its parent. But what if nobody has ever specified a dispatcher in our hierarchy? Well we can simply take a look and then read the documentation. Let’s say we launch a new coroutine and we simply print its current coroutine

01:51:26 - 01:52:26
context. Well there we have it folks. The newly launched coroutine has dispatchers.default as its dispatcher. This is not a result of inheriting it from somewhere, but this is simply the default behavior of the launch builder. If we command click on it and we actually take a look at the documentation for the launch function, it does mention that if the context does not have any other dispatcher then dispatchers.default is used. So this is an important thing to keep in mind when you look at a plain

01:51:56 - 01:52:55
invocation of launch that does not explicitly specify a dispatcher, it is the context that decides which dispatcher things run on. It is either inherited or dispatchers.default is picked if nothing can be inherited. Let’s move on to our next big topic cancellation. We’ve already seen it here and there, but it’s important we lay it out in its entirety to gain a proper understanding of it. We have an understanding of why we need cancellation. We want to avoid doing unnecessary work in general. If you have

01:52:26 - 01:53:19
any contended resources, you want to be able to free them up as quickly as possible if they are no longer used because that keeps your applications responsive. It also helps you avoid memory or resource leaks by not holding on to anything for longer than you really have to. And it is an important part in error handling. Triggering cancellation in coroutines is straightforward. You just cancel the job when it’s appropriate. With launch, you get a reference to the job and you call cancel. With async, you get a reference

01:52:52 - 01:53:48
to deferred, which we already know is a subtype of job. So once again, you just call cancel. A coroutine scope has a job associated with it. So here you can also call coroutine scope dot cancel. And there are also functions that can trigger cancellation of coroutines, one of them being with timeout or null, which cancels the associated coroutine scope after time has elapsed. And of course, it respects the parent-child hierarchy. So all child coroutines are automatically, recursively canceled when

01:53:20 - 01:54:28
the parent is canceled. Visually speaking, in this coroutine hierarchy, if I were to cancel job B, job C and D would also be canceled. And and if we look at this with actual Kotlin code on hand here, we can see that it really is as simple as getting the job reference and calling cancel. If we want to wait for the job to be actually properly canceled, we can also call join or the combine function cancel and join, which suspends until the cancellation has completed. When we are canceling deferred, we also simply call

01:53:54 - 01:54:57
computation dot cancel. Since coroutines started with async are generally responsible for generating some sort of result, you might still have parts of your code that are waiting for a canceled async coroutine. This requires a little bit of nuance that I don’t want to dive in too deeply at this very point, though I do have a reference available for you right on the slides. But I do want to tease your brain a little bit with a small puzzler. Consider the following code where we are creating a new async coroutine, awaiting

01:54:26 - 01:55:17
it, and then canceling it afterwards. What do you reckon happens? Well, the behavior is what you would probably intuit. Once you’ve already awaited it and you’ve already gotten a result, canceling this kind of computation does absolutely nothing. With async, it is quite easy to spot because you’ve already gotten the result out of the deferred, but the same, of course, also occurs for launched coroutines as well. There’s no code remaining that can reasonably be canceled. If we have a

01:54:51 - 01:55:48
component that manages its own lifetime, we also simply call cancel to tear down all the work of all the associated coroutines recursively, which is exactly what we can see on the example on screen. To cancel work that you are doing inside of a coroutine scope builder function, this is a pattern that you’ll often encounter. We start a new coroutine so that we can get an easy job handle on our work, and the detailed work that we want to do, we spawn as child coroutines. If after some time we

01:55:20 - 01:56:21
are no longer interested in the outcome of all of those child coroutines, well, we have a central handle that we can use to cancel all of it. So running this code, we will print bells and cherries for a while, for two seconds, until the work is canceled. At that point, the outermost coroutine scope builder realizes that all its coroutines have finished executing and it itself also completes, so we see the line done printed below. Sometimes you may only be interested in the outcome of a computation as long as it’s below a

01:55:50 - 01:56:53
certain threshold of time. For those scenarios, you can use the with timeout or null function to cap the amount of time that your code runs. Well, it wears its contract on its sleeve somewhat in that you either get back a value before the timeout has exceeded, or if the timeout did exceed, you get back null. The important part here that also ties this back into structured concurrency is that of course, once the timeout has expired, all the coroutines that were started as part of the lambda block of with timeout or null will be

01:56:22 - 01:57:23
canceled. With timeout or null also has a somewhat evil sibling function with timeout, which you may encounter out in the wild, though because it has a couple of serious design flaws, we very very strongly encourage you not to use it yourself. Simply pick with timeout or null for your own code. If you are interested in more details, uh you can take a look at our issues and pull requests in the coroutines library. The fact that these cancellation mechanisms are built right into the library without

01:56:52 - 01:57:56
you having to really do anything extra is a true superpower of structured concurrency, because it allows your code to behave well out of the box. In fact, let’s pop on over to our demo application again for a brief second. Remember that you implemented both the suspending and concurrent loading modes without requiring any kind of understanding of how cancellation works in Kotlin coroutines. Despite this, when I hit cancel before the loading is done, no more work is done on the back end, no more requests are being sent out to

01:57:24 - 01:58:22
fetch more information. Recall that the implementation you wrote for this was the most straightforward one, and still you got the entire power of coroutines-based cancellation out of the box. Now, with the implementation that we used to implement loading of articles concurrently, we already did everything correctly. We simply let ourselves be guided by the shape of the APIs that were provided to us. But just for demonstration purposes, I once again show you what happens if you don’t respect structured concurrency.

01:57:53 - 01:58:58
You are more than welcome to follow along with this exercise yourself. I am moving over to the task three file, which we can find inside the desktop client under JVM main and then tasks again. Well, this implementation didn’t provide us with a coroutine scope, but we still really want to run this code. So we might be once again tempted to use global scope. The IDE is already screams at us, but against our better judgment, we will still try and see what happens. The IDE already screams at us, but

01:58:25 - 01:59:31
we change our return type, and despite the still screaming at us with a large warning against our better judgment, we still run our application. Let me open it up and switch the loading mode to non-cancellable. Now watch what happens if I start the application and immediately cancel, you can see that a whole bunch of work continues to happen in the background. Why? Because we no longer have a hierarchy that allows us to tear down related tasks. In this case, this entire process only takes two seconds, but in

01:58:58 - 02:00:00
production systems, you certainly may have processes that run for minutes or hours. If you lose track of those, it can be pretty bad. So here you have another tangible reason why structured concurrency and cancellation are things that you really want in your systems. But how does this cancellation mechanism work? And are there scenarios where you have to do something to enable cancellation? At its core, a coroutine checks for cancellation whenever it is suspending at a suspension point. This is the behavior that you will get

01:59:29 - 02:00:34
out of the box with all of the functions inside the Kotlinx Coroutines library. So whenever you are calling a suspending function from the Kotlinx Coroutines library, you are adding a potential suspension point to your code, a place where it can be canceled. This specific definition is important to answer the question that I have up here for you. Take a brief look and see if you can spot in how many places this code can be canceled. We have a variable declaration, some loops, a delay, calls to functions foo and bar with their

02:00:01 - 02:01:03
respective implementations. Have you got an answer? Well, let’s take a look. There are a few places where our code can and more notably can’t be canceled. First of all, in our variable declaration and loop, there are no suspension points anywhere in sight, and such no cancellation can occur here. The first real chance of cancellation that we see is the invocation of the delay function. And indeed, this is a suspension point. Now the next line is a little bit tricky because looking only at the code on the

02:00:32 - 02:01:27
left, we see a small suspend function indicator. But looking at the implementation of our function foo, what we can actually spot is that there are no suspension points inside of this function. We never call anything from Kotlin X coroutines. In fact, if we’re looking at it, we can see that the suspend modifier is grayed out. So while it is part of the contract of the function, there are no points where this function could even suspend. As such, in the line where we call foo, no cancellation can occur. There are better

02:01:00 - 02:02:02
news in bar though, because it also is a suspending function and it does call delay with 500 milliseconds. So here it can be canceled again. But it’s a key important thing to remember that just because a function is marked as potentially suspending does not mean that it will in practice actually suspend. I can spend a little bit of time and show this to you in practice. Let me write something up here for a second. So here I just wrote up a very short function called spin, which all it does is it prints a new random number every

02:01:31 - 02:02:30
100 milliseconds. Can this function be canceled? Well, our understanding should tell us by now that yes, but let’s put it to the test. We’ll We’ll start a new coroutine, invoke the spin function, grab ourselves the job, delay for a little bit just so that we can see that it’s actually working, and then cancel that coroutine. Let’s run it and observe its behavior. Well, we can see that it certainly printed a couple of numbers and then stopped. So we successfully canceled it. My question to

02:02:00 - 02:02:59
you now is, how does this change if I lower this delay to 0 milliseconds? Well, well, let’s put it to the test. And indeed, despite attempting to cancel after 500 milliseconds, our code just keeps on running and it keeps printing random numbers until I forcefully kill the process. The reason for this is exactly the statement that I made before. Just because a function can potentially suspend doesn’t mean it will suspend. Let’s take a look at the implementation of delay. In the very first line of the implementation,

02:02:29 - 02:03:29
we can see that there is a a path. Well, so if I am delaying for 0 milliseconds, this function does nothing. It returns immediately. As such, calling delay with a number that is zero or negative makes no sense. It does nothing to help with the cancelability of your code because it does not introduce a new suspension point. The whole world changes when you move to 1 millisecond, but there are better ways to manage this instead. So we have seen that when held correctly, library functions are cancelable, but

02:03:00 - 02:04:03
this does not necessarily extend out of the box to your own code. Just because your function is marked as suspend does not mean that it necessarily is cancelable. If I only give you the snippet of code that you can see here, it is impossible to tell whether do CPU-heavy work can be canceled or not. This is the core part of how cancellation works in coroutines. Cancellation is cooperative. Your code needs to actively do some things in order to support cancellation. We’ve already talked at length about why you

02:03:32 - 02:04:32
want the cancellation. Let’s talk about the how. There are a number of functions in the Kotlin X coroutines library that allow your code to cooperate with cancellation. Whenever you have a coroutine scope, you can call the is active property. If this property is false, you know that somebody requested cancellation of this coroutine scope. Since this is just a boolean, if you want to do some finishing work after checking that before wrapping up, you can do that. You can free up some resources and so on. As an alternative,

02:04:02 - 02:05:01
you can also pick the ensure active function. Ensure active also checks if a cancellation was requested, but rather than just giving you a boolean, this is a proper cancellation point. Here, a cancellation exception, which is the signal that is being used by the coroutines machinery to propagate cancellations across the hierarchy, is thrown immediately and work is stopped immediately, too. Of course, since the mechanism that’s used here is that a cancellation exception is thrown, is that finally blocks will still run. So

02:04:32 - 02:05:34
you still have a chance to clean up some resources, for example. The yield function is particularly useful because it also checks if cancellation was requested, but in addition to that, it also relinquishes also have the chance to still run on the same shared dispatcher that might otherwise get exhausted. In this snippet, for example, we are doing 10 repeats of some CPU-intensive work. If the function itself is not cancelable, we can work around this by checking for is active and in that case, returning

02:05:12 - 02:06:17
out of our coroutine. Alternatively, we can also call the ensure active function, which will throw a cancellation exception if we have been canceled. That way, at most, we are finishing our last iteration of due CPU-heavy work and don’t enter additional unnecessary work. But like I said, especially when we are doing CPU-heavy work, the nicest way to treat the situation would be to use yield. It still introduces a cancellation point, but it also lets other coroutines that want to use the same dispatcher play and work. I always

02:05:45 - 02:06:45
find that visualizations can kind of help get a better understanding of the difference between these. So let’s take a look at those here. Let’s consider for simplicity work on a single-threaded dispatcher and we are trying to get two jobs done. If we have no cancellation or suspension points, then we will simply execute the entirety of task A first and then the entirety of task B. If we can find a place inside the implementation of task A to call is active or ensure active, then within the individual task,

02:06:15 - 02:07:24
we have certain points where we can cancel. Note, however, that despite checking for cancellation, task A does not relinquish any of the underlying resources. It keeps working on the thread. It is only by choosing yield where both tasks, A and B, get a chance to take turns using the underlying single-threaded dispatcher. Both tasks can make progress and both tasks can be canceled at multiple intervals. I hope this explanation makes it I hope this explanation clears it up a little of why yield is best used in general purpose

02:06:49 - 02:07:55
application code, especially that one that does computations that are CPU intensive. Like we briefly talked about when talking about ensure active, the actual signal that is used by the coroutines machinery to propagate cancellation across hierarchies is the cancellation exception. As such, this specific type of exception can be expected to be thrown in regular code that may be canceled. That’s perfectly normal, but it also requires you to add a little bit of extra care when you write code that handles exceptions. Let

02:07:23 - 02:08:29
me show you what I mean right here. We are back in IntelliJ with yet another small sample. We are starting a polling job which simply loops and does some sort of operation. It doesn’t really matter which one every half second. Because this polling operation might fail for some reason, here we have decided to simply catch all and every exception and simply print it without doing anything else with this kind of exception. After 3 seconds, we simply invoke cancel. We can do a quick mental check. There is a

02:07:56 - 02:08:52
delay function here, so we are calling something from Kotlinx coroutines. We have a cancellation point. Our code should be cancelable. So what might the problem with this code then be? Well, running this code, we see a couple of instances of polling and then after the cancellation hits, all of a sudden we see a lot of standalone coroutine was canceled and it keeps repeating on polling. Let me stop that for a second before my computer overheats. The problem is that delay, like any other function that introduces a cancellation

02:08:24 - 02:09:21
point in your code, throws a cancellation exception when the surrounding coroutine was canceled. And like I mentioned, this is a very ordinary case. We simply weren’t interested in this code anymore, so we wanted to stop it. But the problem lies in exactly the next line. For reasons of perhaps laziness or overcautiousness, we simply decided catch all exceptions and just log them. But in the process, we prevented the cancellation exception from doing its job, from stopping the work that was happening in this block.

02:08:53 - 02:09:53
And this is a particularly annoying problem to introduce for another reason. Since in this particular case, everything is happening in a loop, once the coroutine was canceled, delay will always immediately rethrow a cancellation exception over and over and over again. And most importantly, it won’t delay. So now we effectively just have a while true loop that just keeps printing polling and problem however fast your computer can do it, which is precisely why you should take my next advice to heart.

02:09:23 - 02:10:25
Your code should not swallow cancellation exception. You need to be careful about what specific types of exceptions you catch in your application code because cancellation is a normal thing that can and will happen. The coroutine’s machinery relies on cancellation exceptions as signals to propagate cancellation. And as we have seen, taking away this ability to signal cancellation can result in some really nasty problems. There are a couple of approaches that you can take to defend against this problem. The first and

02:09:54 - 02:10:53
certainly the most intuitive one is to simply not catch them in the first place. Rather than catching all of exception or all of throwable, figure out which cases you can actually reasonably handle and then catch those. Alternatively, in your catch block, you can check for cancellation exception. You just do a type check and see if the exception you have received is a cancellation exception. And then you can either rethrow that exception verbatim or you can invoke the ensure active function right then and there, which also

02:10:24 - 02:11:16
triggers the propagation. The latter effectively says that, okay, in my code there appears to have been a cancellation exception. Let me just check that I’m still active. So let’s go back to IntelliJ and fix our problem using these approaches. The most basic example would be having a better understanding of my own code and saying that maybe this is a number format exception. In this case, re-running the code, since we will not encounter a number of format exception, we will simply poll for a

02:10:50 - 02:11:53
while and then quit. But alternatively, if we want to keep the broad uh exception catcher here, we can instead use a type check. So we can just say if e is cancellation exception. And in that case, we will just throw e again. We don’t treat it as an exception in the classical case. We just re-throw it because we know it is a signal. Once again, running this code, we see that after a couple of seconds of polling, things are indeed canceled correctly. The alternative approach here would be to call ensure active after the type

02:11:22 - 02:12:15
check. This effectively gives you the same result as just re-throwing, but it defends you against the very rare case that your code encounters a cancellation exception that wasn’t specifically meant for your code. Again, this is a very rare case. So if you want to understand the rationale for where to use this pattern specifically, I’ll put on some extra info on the screen. To understand whether any of your code currently could catch cancellation exception, it makes sense to take a look at where

02:11:48 - 02:12:46
cancellation exception sits in the class hierarchy. It itself is a subclass of illegal state exception, which makes it also a subclass of runtime exception, exception, and throwable. So if you have catch blocks in your application code that catch any of those, it might be worth seeing whether you need to defend against the cancellation exception swallowing here. If you are continuing to follow along at home, you can open up the task one CPU heavy work and task two cancellation exception tasks. Here you

02:12:17 - 02:13:16
can find some code that exhibits some of the problems that we’ve talked about. Specifically running this code, we notice that despite a request to cancel and join after 1 second, this code just seems to continue working. I’ll give you a couple of seconds to pause if you want to fix this culprit on your own. Got something? Okay. Well, indeed there are a couple of different ways of how we can fix this. [sighs and gasps] We could check for is active, for example, and then simply return out of our coroutine. That would

02:12:47 - 02:13:46
be a valid fix, and our process finishes correctly. The same will work with ensure active, but as we discussed, the nicest solution given that we are doing some CPU heavy work here, incrementing counters over and over again, the nicest solution would be to simply use yield. Our code cancels correctly, and if there had been any other coroutines that were contending for this dispatcher, they would have also gotten a chance to run. In test two, we find ourselves yet again in another familiar situation. We see a

02:13:16 - 02:14:11
spam of standalone coroutine was canceled. Once again, I’ll give you a couple of seconds to ponder what solutions we have learned about that can fix this problem. Got something? Very good. Indeed, our culprit was once again that we are catching too many exceptions and intercepting the cancellation exception signal from the coroutine’s machinery. We have seen different kinds of approaches. The one that I would choose here is given that I know the type of exception that might be thrown here is that I would only catch this

02:13:44 - 02:14:55
specific subtype. Rerunning the application, we can see that the process finishes correctly despite some exception being caught. If for some reason I had the requirement of catching all of exception, then I would probably check and see if my E is a cancellation exception, and in that case, I would just call ensure active. This is also one of the problems that people who love using run catching might run into. The contract of run catching is that it encapsulates any throwables that were thrown from the block during

02:14:19 - 02:15:19
its execution. But as we have seen, cancellation exception, the signal for cancellation coroutines is also a subtype of throwable. So using run catching intercepts this important coroutine signal. As such, our general advice is to not use run catching in your application code. If you want to dive more deeply into the discussion about run catching and its relationship with coroutines, there is an issue on the Kotlin coroutines issue tracker. You can check that out if you are interested. Extending beyond this

02:14:49 - 02:15:48
specific signaling topic, it is of course also important that any code that you write that may be canceled behaves as a good citizen. That means it should close its resources, for example. If you have a block that can be potentially canceled, then you can just use a finally block and you can mop up some resources there. The common standard library also provides you with additional helpers that can make this easier. For example, the dot use function that automatically closes auto closables once the scope is

02:15:18 - 02:16:17
over. And it itself is also a function that behaves well when being canceled. It is also important that your code follow the principle of prompt cancellation, which effectively says that once you’ve been canceled, your application code should not resume normally from suspensions. It should promptly cancel. For the case where you need to call suspending functions as part of your cleanup after you’ve already been canceled, you can use the special non-cancelable context element which you can use together with the with

02:15:48 - 02:16:48
context builder function to invoke suspension functions even though the outside scope had already been canceled. It is a special job type that allows you to briefly work around the fact that your coroutine scope was already canceled, but it is only designed specifically to be used with context in such operations. You should not parameterize launch or async using non-cancelable. On the left side, we have a component with a root scope, as we have seen a couple of times. Though I would like to once again remind you that

02:16:18 - 02:17:21
in an ideal case, you would always connect up to another parent scope. On the right side, we see the typical pattern of using non-cancelable. We create the component and have it begin some work. It is then waiting for cancellation, and in the finally block, we use the non-cancelable job object together with with context, not just to tear down the component scope for our component, but to do any other suspending cleanup that might be necessary. And of course, the main point is that this cleanup block inside of

02:16:49 - 02:17:53
with context will still run even if surrounding coroutine scope where we did all of this work was already canceled. By the way, it is perhaps also worth pointing out at this point that cancellation is a one-way process. It cannot be undone. There’s no such thing as uncancellation. You can see this quite easily by taking a look at the different states that an individual coroutine can be in. You can tell by looking at the arrows that they only go in one direction. So there is no way for a canceled coroutine to once again

02:17:22 - 02:18:18
become active. If you do have more work that you need to continue after cancellation, the answer is quite simple. You just have to start a new coroutine. Thankfully, they are extremely cheap, so that shouldn’t be a problem. Now, before we wrap all of this up with a bit of a summary, there is one more point that we discussed previously that becomes relevant here again, and that is that cansability and main safety go hand in hand. Previously, we talked about the concept of moving away heavy work to dedicated dispatchers to free

02:17:50 - 02:18:48
the original dispatchers to do something else. That way, we avoid blocking the callers of our suspending functions. To make the function a proper good citizen in the coroutine’s ecosystem, we also just need to take cansability into account. So on the one hand, we have with context to switch to a dedicated dispatcher, and then on the other hand, we also call ensure active to participate in cancellation. And with that, [clears throat] you end up with a function that is both non-blocking and cancelable. And as such, it’s a pattern

02:18:18 - 02:19:18
that is really worth embracing. Let’s now move our attention to error handling in the context of coroutines, and let’s answer some of the exceptional questions that might come up. Things like, how do we behave when a coroutine breaks? If a child coroutine throws an uncaught exception, what is supposed to happen? What is supposed to happen to its siblings? What is supposed to happen to its parent coroutine? By getting answers to exactly these kind of questions, we’ll develop a better understanding of

02:18:48 - 02:19:49
how exceptions propagate in coroutine hierarchies. Before we dive deeply into the mechanics of how the coroutine machinery handles exceptions. First, let me offer you a little bit of advice. Because code that runs inside of a single coroutine is sequential, the error handling approach here is also very straightforward. You can simply use try catch. It still works exactly as you expect. And precisely because you don’t need to make any differentiation here, this is also the preferred way of handling exceptions. If you can, simply

02:19:19 - 02:20:06
don’t let them cross coroutine boundaries. We can see that in this snippet right here. We’re doing some work that may fail, and we catch the some work exception and handle it in some way. And because we are experienced coroutine engineers, as we wrote this code, we of course always kept in mind that there shouldn’t be a situation where we catch cancellation exception. Now, there is a code snippet like the one on the slide here that we sometimes encounter out in the wild, which is why

02:19:42 - 02:20:39
I wanted to briefly talk about it. There is no point in wrapping coroutine builders like launch or async in try catch. That’s because the thing that they do is start a new coroutine and return immediately. If that coroutine fails at a later point, you will have long left the try block, so there will be nothing to catch. Hopefully, this isn’t a particularly surprising insight at this point, but I did want to point it out because we sometimes see confusion around this. So, as I said, try catch remains the

02:20:11 - 02:21:06
preferred way of handling exceptions even when you find yourself in the world of coroutines, because it means that the exceptions remain confined to an individual coroutine, and it also means that you can use the power of the sequential code abstractions that we have to easily reason about the kind of code that handles your errors. But of course, we also recognize that there are situations where you might find yourself with an exception that was not caught within a single coroutine. And here we

02:20:39 - 02:21:42
need to answer the key question of what happens when that exception remains uncaught. The general principle that we see here, if we have a bunch of child coroutines and a parent coroutine that has a regular job installed, is that when a child coroutine fails, it cancels all of its siblings. What precisely happens is that the child coroutine escalates its failure to its parent coroutine. The parent coroutine then takes care of canceling all the other coroutines, and at that point the parent also cancels

02:21:10 - 02:22:17
itself and propagates the exception further up the hierarchy. And to be clear, whether those coroutines were started using async or launch does not matter at this point. This kind of propagation may seem excessive or perhaps at least intense at first sight. It seems that one rogue exception can tear down the entirety of your application. But what we are really witnessing here is the superpower of structured concurrency once again. And there is a reason why this is the default behavior that you get out of the box, because the

02:21:43 - 02:22:47
default assumption is that coroutines collaborate. They work together in a system where they rely on each other to do some work together. Now, if in such a system a coroutine fails with an uncaught exception, then most likely the collaboration with all the other coroutines will not be able to continue. And if all of the work that those related coroutines do can’t be used anymore, well, then the only logical conclusion is to cancel those coroutines as well to avoid unnecessary work. That includes the children of the failed

02:22:16 - 02:23:16
coroutine. Of course, it includes the siblings, but it also includes the parents. Now, the important part to note here is of course that this is just the behavior that you get out of the box. You as the person in charge of building the system may simply know better, because as you construct your system, you have an understanding of which coroutines belong together and which ones don’t, which coroutines need each other and which coroutines can happily exist even without some of the other ones. To codify this knowledge and make

02:22:45 - 02:23:58
your system act accordingly, we need a mechanism to introduce error boundaries, effectively places in your hierarchy where exceptions stop propagating. And this is precisely the role that supervisor jobs fill. They’re a special type of job that acts as an error boundary. Just like any regular job, a supervisor job can be placed in the coroutine context. But unlike job whose behavior it is to cancel siblings itself and then parents, the supervisor job prevents the cancellation of those. So the siblings of a coroutine that threw

02:23:22 - 02:24:22
an uncaught exception and couldn’t work anymore, those keep running. The exception isn’t propagated further up the hierarchy. So grandparents of the crashed coroutine also keep running and of course the parent itself. Here is what this prevention of propagation looks like visually. We once again have four coroutines, some started with launch, some with async, but this time the parent scope has a supervisor job installed. When our leftmost child coroutine throws an uncaught exception, it tries to propagate this exception to

02:23:52 - 02:24:50
the parent. But because the parent has a supervisor job installed, the supervisor does not handle this in any way. It does not cancel the other children nor does it propagate the exception further up the hierarchy. In effect, it simply ignores it and by virtue of that keeps the rest of the system running. There are multiple places and ways on how you can get your hands on a coroutine scope that has a supervisor job installed in it. In many cases you may get a supervisor from a framework. For example, in Ktor, individual request

02:24:21 - 02:25:21
handlers are isolated using a supervisor. That’s why when an individual request handler fails, other request handlers continue running. There’s also a sibling builder function to the coroutine scope builder function called supervisor scope and it behaves analogous to coroutine scope, but it has a supervisor installed, which changes its behavior when any of the child coroutines encounter an uncaught exception. Another place where you can install a supervisor is of course when you are creating components. For

02:24:51 - 02:25:50
example, if they have an externally managed lifecycle or lifetime, that’s when you use the coroutine scope constructor function and as part of its context you would pass a supervisor job. Let’s see my preferred way of creating my own supervisor using the supervisor scope builder function in action in IntelliJ. Let’s say we find ourselves in the following code. Here I have a coroutine scope where I have two coroutines that are independently computing two separate numbers. Baseline number just takes two seconds and

02:25:20 - 02:26:11
returns 800. Bonus number, however, already after 100 milliseconds fails its execution with an uncaught exception. Let’s say we want to protect ourselves against one of these coroutines failing like the one that we have here. Well, if we simply want to keep the coroutines running, we would switch our coroutine scope for a supervisor scope. At this point, the uncaught exception of one of the coroutines won’t affect the execution of the other. There is still one additional change here though that

02:25:46 - 02:26:51
we need to make to the code, and it relates to the semantics of await. We haven’t talked about this in any detail up until this point, so now is as good a time as any. The specific behavior of async coroutines is that when an exception is thrown, this exception is stored and rethrown when await is called. The idea here is that since async computes a value and there is another party, our code down here that is interested in that result, we should also give that code the opportunity to handle different

02:26:18 - 02:27:34
errors in different ways. For us, this means that we need one more try-catch block before our code is ready to run. We’ll create a new bonus variable which will try to await the bonus number. In the case where we are catching a my exception, we can instead provide, for example, a default bonus. We’ll set it to 100. We of course also want to update our total calculation to use this new bonus variable. And if we expected that baseline number could also potentially fail, well, we would repeat this pattern as well. We

02:26:57 - 02:28:05
can now run this code and see how it behaves. We can see that despite one of the coroutines failing, the other coroutine continues running for its full length of two seconds and then returns 800. We can also see that the catch block was hit when we called await. As such, we arrive at the total value of 900. This specific this specific pattern of using a supervisor scope together with async coroutines and then wrapping the await call in try catch is quite a popular one, which is why I wanted to derive it from well somewhat first

02:27:30 - 02:28:26
principles here. It is useful whenever you have multiple async computations, but you can still reasonably generate a result even if one of them fails. And you get full control over how to handle the exceptions wherever you are actually using those values. Here I wanted to specifically show you this style of pattern. However, there is an even better way to handle these kind of problems. If you remember from the beginning of the section, the easiest way to handle exceptions in coroutines is to not let them cross coroutine

02:27:58 - 02:28:59
boundaries. Now it might look a little bit silly in this example, but a better way is to move our code that may potentially throw an exception into a try block, catch the potential exception, and then return some sort of default value. Now we don’t even have an exception that propagates across coroutine boundaries, and whoever awaits this bonus number will simply unpack the default value of 100 directly. This just once again goes to show you that if you can keep exceptions constrained to a single coroutine, things just become a

02:28:29 - 02:29:27
lot easier. But let’s get back to our discussion of where we can actually get these kind of supervisor scopes from. Right now we just saw one in action. If you have a component with a life cycle, as in if you have a component that has a coroutine scope associated with it, then you can simply replace the job with a supervisor job. And it still makes sense to wire up this supervisor job to a parent scope’s job if you have the opportunity. Because while the supervisor job introduces an error

02:28:58 - 02:29:58
boundary for all the child coroutines that are started on the component’s scope, by wiring it up to another parent job, it still retains the ability to cancel all of these things in a coherent manner. In other words, when some overarching component is canceled, then the coroutines associated with my component will also be canceled as well. As such, you often see these types of supervisors living quite far up the hierarchy of your coroutines. They’re often scoped to the lifetime of your application, a window, or a screen.

02:29:28 - 02:30:28
Precisely the kind of use cases like you see in Ktor, where they isolate individual request handlers. They are also not designed to replace try-catch error handling. Wherever you can simply use try-catch, please do so. The accompanying demo application for this course actually has a small problem baked right in that demonstrates how important it is to put supervisors in certain positions. Let me show it to you. Here’s the demo application, and I have selected the unstable network loading mode. In this mode, there’s a high

02:29:58 - 02:31:00
chance that one of the requests going out will trigger an error as part of its response. By default, the code that invokes this loading runs under a regular job, not a supervisor. So let’s see what happens here. After hitting load comments, I end up in a loading status of failed. So far still perhaps okay, but unfortunately, at this point, we are no longer able to make any other loading progress at all. We can see that nothing loads anymore even when I change the loading mode. So what’s up with

02:30:29 - 02:31:25
that? Well, let’s dive in and investigate. The code responsible for loading this information is part of the article’s view model, which you can see as part of the desktop client project. For demonstration purposes, there is a specialized loading scope that is used to load this information, which simply has a job. Well, and if we recall the behavior of a coroutine scope that has a regular job inside it, the behavior shouldn’t surprise us. Once one of our coroutines has failed with an uncaught

02:30:57 - 02:32:01
exception, the coroutine scope is canceled, and so are its siblings. So let me switch this out with a supervisor job that introduces an error boundary. Restarting the application and moving back to the unstable network, we can now load things and they do indeed fail. However, if I go back to, for example, the concurrent loading mode, we can already see it in the background and then also in the UI, things load just as we expected to. Here we used a supervisor scope to prevent an unexpected uncaught exception from

02:31:29 - 02:32:30
tearing down the entirety of the system. By the way, as you probably noticed, I had to create a specific demonstration scope for this to really demonstrate this because it doesn’t match the behavior of an application in real life. But all in the service of understanding. So in short, supervisors deal with the failure of child coroutines by simply ignoring that failure. The child coroutine would like to propagate its exception up the hierarchy further, but the supervisor stops that from occurring. Now, when we are talking

02:31:59 - 02:33:03
about coroutines that were started using the launch coroutines builder, there is one more subject we need to talk about because there’s a special context element called coroutine exception handler that allows you to do some last resort handling of uncaught exceptions for those coroutines specifically. What effectively happens is what we can see here on the screen. Let’s say we have a coroutine that was started using the launch coroutine builder. It throws an uncaught exception. Well, its direct parent is a coroutine

02:32:31 - 02:33:34
that has a supervisor job installed in its context. As such, the launch coroutine tries to propagate its exception to the parent. However, like we have discussed before, a supervisor job does not handle child failures. It declines handling it. As such, as a last resort, the launch coroutine invokes its coroutine exception handler. This coroutine exception handler is simply a function that can be invoked to collect some information or do, for example, some logging. So why does this coroutine exception

02:33:03 - 02:34:01
handler function exist and why does it only affect coroutines that are started using the launch builder? Well, the reasoning is this. When you start a coroutine using launch, they are kind of fire and forget. Where a coroutine started using async has a pretty obvious recipient, whoever awaits the result, a coroutine started using launch doesn’t really have an equivalent. But the coroutine’s machinery still recognizes that it’s probably a good idea to tell somebody in some way about the failure of this

02:33:32 - 02:34:28
coroutine. And this is precisely why the coroutine exception handler exists as a last resort approach. You can use it for the most basic ways of doing things like diagnostics. You can report failure to the users or log them. But from inside the coroutine exception handler, there is no way to recover. The coroutine has completed exceptionally. Once again, at the risk of repeating myself to an incredible degree, whenever you can, prefer try catch. It fundamentally just exists as a coroutine context element

02:34:00 - 02:34:54
and is subject to all the rules of coroutine context elements. For example, the coroutine exception handler is passed down the inheritance hierarchy like any other element as well. It is perhaps interesting to note that by default, when you don’t provide anything custom, the coroutine exception handler delegates to thread.default uncaught exception handler. And this has slightly different implications depending on the platform that you target using Kotlin. On the desktop JVM, you simply get a log

02:34:27 - 02:35:24
message to standard error. However, on both Android and on iOS, these will automatically crash your application. But of course, you can also provide your own alternative coroutine exception handler to do those last resort things. You can define a custom coroutine exception handler by using its SAM constructor. You can see that at the top here where we just use coroutine exception handler, provide its two parameters, the coroutine context which we ignore here with an underscore and the exception of type Throwable. And we

02:34:56 - 02:36:03
simply use it to print some information like the fact that we got an exception. Using it is pretty simple, too. You can add it to any coroutine’s context like any other context element, for example, by providing it to the launch builder. However, it is important to note that the coroutine exception handler only takes effect if the direct parent of the coroutine is a supervisor. This might appear a little bit tricky at times like for example in this snippet where we have a supervisor scope function but then use with context to

02:35:29 - 02:36:32
add the exception handler. We might expect that the error that we get in the launch coroutine propagates to the exception handler because we are inside of a supervisor scope. But looking more closely, we have invoked a separate coroutine builder in the middle here and with context has made us the child of a regular non-supervisor job. Flipping these lines, so first installing the context element of the coroutine exception handler, then opening a supervisor scope and then calling launch which simply inherits

02:36:00 - 02:37:00
this coroutine exception handler works as expected. This is just an important nuance that you need to keep in mind as you play around with coroutine exception handlers. Like we have seen in some of the previous examples, the coroutine exception handler that matters is the one that is associated with the failing coroutine that has a supervisor as its parent. As such, it is absolutely possible to specify a coroutine exception handler for a single coroutine by parameterizing its builder like here how we do it with launch. Though again,

02:36:30 - 02:37:29
it only takes effect if the direct parent of the failing coroutine is a supervisor. But like previously already briefly mentioned, since the coroutine exception handler is simply a coroutine context element, it also follows the inheritance hierarchy. In this example, the coroutine scope that is associated with our component specifies the coroutine exception handler. When later on our newly started child coroutine inside of the do work function fails, this coroutine exception handler is still invoked. That’s because this

02:37:00 - 02:37:55
coroutine inherited the coroutine exception handler. So after it has checked that it is the child of a supervisor, this coroutine does indeed invoke the inherited coroutine exception handler. And of course, all other child coroutines also inherit this coroutine exception handler. Our discussion around the coroutines exception handler was focused entirely around coroutines that were started using the launch coroutine builder. Our motivation behind this was that launch doesn’t have a recipient of the

02:37:27 - 02:38:24
computation. So let us cover once more the computations that do have a recipient. Those coroutines started with async. Here coroutine exception handler doesn’t play a role. It is entirely a concept that only relates to launch coroutines. Instead, when an uncaught exception occurs, this exception is stored in the deferred. But to keep consistent with structure concurrency, the exception is of course still propagated to the parent as we would expect. If the parent is a supervisor, well, that exception propagation is

02:37:55 - 02:38:56
ignored. And for a regular job, we get the default behavior where other siblings are canceled and the exception is propagated upwards. The key point that may also influence how you write your code is that the exception is rethrown whenever you call await on a deferred of a coroutine that previously failed. So if you can reasonably expect and handle certain exceptions, you should use await together with try catch. It is also important to note here that await will rethrow this exception whenever you call it, not just at the

02:38:26 - 02:39:28
first time. And again, the core logic here is that with async you have someone awaiting the result and they should have to be able to decide on how to recover from a failure. Here’s the same story again visually. This time our failed coroutine was started using the async builder. When it throws the exception, it is stored in the deferred. And additionally, this coroutine tries to propagate its exception to its parent. In this case, we once again have a supervisor job sitting in the parent coroutine scope again, which declines

02:38:57 - 02:39:58
handling regardless of whether the parent decides to handle the exception or decline handling, when somebody calls await, they will get the exception thrown that was originally happening inside of the async builder. And since what await throws is just a run-of-the-mill exception, we use try catch to handle it. Here is an example of this. We launch a coroutine that just runs a couple of heartbeats to make sure that we can actually see that our application keeps running. Then we start some work that is going to throw eventually. In

02:39:28 - 02:40:24
order to handle the potential exception, we wrap our await call in try catch and catch the specific exception that we are interested in and can handle. Since we are in a supervisor scope, the failure of async does not influence the running of launch. Because await throws an exception of a type that we know, handle exception is invoked. Even though we see a bunch of different pieces fitting together here, it should still be rather straightforward. In general, exceptions propagate up the hierarchy of coroutines

02:39:56 - 02:40:50
until they hit a supervisor. For uncaught exceptions with launch, the coroutine exception handler of the crashed coroutine is called when the direct parent doesn’t handle the exception. So when it’s the direct child of a supervisor or there is no parent to handle things. You can customize the behavior of the coroutine exception handler by providing it as a coroutine context element, but by default the coroutine exception handler behavior is slightly different per platform because it delegates to the

02:40:23 - 02:41:20
thread default uncaught exception handler. On the JVM, it simply prints the error and on Android and Kotlin Native it will crash your application. For coroutines started with async, regular structured concurrency rules apply with the addition that when you call await, this will rethrow the exception that was encountered. Let’s also recap what the key recommendations are in this regard. First of all, the easiest way to avoid dealing with any of this is to simply avoid uncaught exceptions having crossed

02:40:51 - 02:41:49
coroutine boundaries in the first place. By wrapping the code that may potentially throw exceptions directly in try catch and handling the error then and there, you don’t have to deal with any of this extra complexity. The simplest way is to just use try catch around the code that may potentially throw an exception. And of course, by now you already know to exclude or rethrow cancellation exception if you need to broadly catch exceptions. If you are in full control of the system, you may also choose to use other mechanisms

02:41:20 - 02:42:15
to indicate failure. So rather than having your code throw exceptions in the first place, you could use sealed result types. Supervisors are a particularly useful tool because they allow you to introduce error boundaries in your coroutine hierarchies. So as you architect your applications, the placement of supervisors is one of the aspects that you should definitely pay attention to. When you are working with async and await, then you handle these exceptions explicitly wherever you call await. And if you want specific insights

02:41:48 - 02:42:45
into what has gone wrong with coroutines that were started using launch, you can specify a custom coroutine exception handler that will be inherited to all the child coroutines. Here you can do logging, you can do analytics, anything like that. At this point, we have covered all the major points when it comes to coroutines, structure concurrency, and even error handling. But the tools that the coroutines library puts in your hands extend beyond this. I’m talking about our reactive abstraction, flows,

02:42:16 - 02:43:18
which we’ll cover next. Because so far, when we were talking about suspend functions, there was one limitation that we kind of simply accepted, and that is that a suspend function always computes a single value. Even if we have a function like this called get from network, which returns us a list of string. While yes, it returns multiple strings, it returns us a single object at a single instance in time which contains all of those strings. But sometimes returning a single value at a single point in time might not be

02:42:48 - 02:43:46
enough. You may want to return multiple values over time. That’s typically used when you do stuff like progressive loading, for example, or you have a computation where intermediate results are also valuable in some way. You may also want to build parts of your systems that stream out events, for example. Or you want to be able to build subscription-style APIs where subscribers are notified as new things happen. And to do all of this in the world of coroutines, well, we do need a coroutine-based abstraction for it.

02:43:16 - 02:44:19
And that is precisely what the flow type represents. A sequential stream of values that are being computed asynchronously over time. Our function that previously may have suspended and then after its suspension have returned us a single large list of strings now returns us a flow of strings, effectively a collection that is returned over time. It is also noteworthy that due to the structure of how flows are constructed, this function no longer needs to be suspend. We’ll see that in just a little bit. The

02:43:48 - 02:44:51
coroutines library exposes a number of different specific types of flows that you can use. They are generally categorized into cold flows and hot flows. Cold flows are constructed using the flow and channel flow builder as we’ll see later on. Hot flows, on the other hand, with shared flow and state flow are always active. We will see the specifics of each of these types of flows as we continue through this section. For now, I just want you to take away that both cold flows and hot flows are the key abstraction that we

02:44:20 - 02:45:21
have when we’re talking about flows. They are not always cold or always hot. You can choose the correct type of flow for what you try to achieve. Let’s begin our discussion by first talking about cold flows. And let’s simply begin by creating our first cold flow. We do this exactly as displayed here. We use the flow builder function to create a cold flow. With cold flows, no work is done yet. So we are effectively defining a recipe of what should happen once somebody collects this flow. Inside of

02:44:50 - 02:45:52
the flow builder lambda, there is really only one special thing that we can do, and that is call emit. This offers a generated value to a collector. So we simply invoke the flow function, we do some computations, and once we’re ready, we call emit to offer them to the collector. Because a flow constructed using a cold flow builder function doesn’t start doing any work yet, it is totally okay to write something like this. Here we have a flow that simply infinitely emits ever increasing numbers. And that is totally fine. We

02:45:21 - 02:46:20
can also note here that since we are working with a coroutine-based abstraction, it is also totally okay for this flow lambda to suspend. Here we’re just calling delay 200, but you could also imagine, for example, waiting for a remote service to reply. But note that we can still store this flow in our counter flow variable. Why? Because we are really just defining a recipe here. No work happens until we actually collect this flow. So let’s do that next. Here’s a snippet that collects a

02:45:50 - 02:46:52
flow of user uploads, for example. And this invocation of collect is what kicks off the logic that happens inside the previously defined flow. Collect is a suspending function which suspends until the entire flow has been collected. And you can probably guess what that means for an infinite flow. Either it keeps collecting forever or somebody gets canceled. Inside of the collect lambda, you can make other suspending calls. So you can do more meaningful work with the flow results. In this case, we’re persisting data

02:46:21 - 02:47:13
using another suspending API. Let’s try this ourselves in the IDE. Let’s define our flow ourselves that generates a couple of numbers. In here for now, let’s just emit a couple of numbers. Here we have effectively defined the recipe of what a collector of this cold flow should do when it starts collecting it. Looking at the signature of the flow builder, we see that indeed the lambda that is passed to it is a suspend lambda, which allows us to invoke, for example, other suspending functions.

02:46:47 - 02:47:45
So if I wanted to, I could add a delay of 200 milliseconds here. Because no work is done by defining this, there is no reason for me to do this inside of the coroutine scope. I may as well define it as a top-level property. Let us now collect this flow and print out the numbers. I’ll call collect, and I can once again see that the individual numbers, the individual values that were offered by emit will be made available to me as the parameter. By default, that is named it, but I could also, for example, rename it

02:47:16 - 02:48:13
to number. And then I could, for example, just print this number. Running this code, we do indeed see that numbers zero through four are printed correctly. Because these flows are cold and you can kind of think of them as a recipe, you might also be able to develop an intuition of what happens if I collect the same flow once more. Since with cold flows, the collector is entirely responsible of executing the code of the flow, here we will see the same numbers printed out twice. And indeed, we simply see the

02:47:44 - 02:48:42
numbers from zero through four printed twice one after the other. This is an important thing to note for cold flows. The collector runs what we call the upstream flow for itself. There’s no sharing or anything like that happening between different invocations of collect. Like we have seen before, nothing is stopping us from defining a flow to return an infinite number of values either. But of course, in this scenario, trying to connect this flow one after the other doesn’t really make a lot of sense.

02:48:14 - 02:49:16
After all, this first invocation of collect will suspend until all elements have been received from this flow. And with a while true loop, well, we’re never reaching that end. Of course, we could simply wrap this in a launch block though. And we could do the same thing twice to collect the same flow twice independently. So, for example, we may have coroutines A and B collecting this flow. Let me dial down the speed just a little bit so that we don’t get overwhelmed. And indeed, now we have two coroutines

02:48:45 - 02:49:44
independently running their infinite flow and collecting elements from it. What is perhaps also already interesting to note here is that there is kind of a ping pong effect between the collector and the flow lambda that generates these values. We can see this more clearly if we focus on a single collector here. If the collect lambda also suspends, we can see that it takes four seconds for a new value to be generated. So, what effectively happens is that the delay is invoked, then emit is invoked, which

02:49:14 - 02:50:19
moves the control flow over to our collect lambda. Some work is done. We pause for another two seconds, and at this point, the collect lambda has finished. So, control flow is returned back up to the lambda associated with the flow builder, which just continues with the next loop. You can hopefully see how there’s 4,000 milliseconds worth of work happening there. And just to be a bit of a completionist here, we can also show you that, of course, you still have a way of getting out of an infinite flow simply by

02:49:47 - 02:50:46
canceling the coroutine that does indeed collect the flow. So here we get one value generated, and after that our job is indeed canceled. This is a good time for us to introduce our second project, which is our kettle simulator. It’s a very simple program that simulates a water kettle, like the one that you use for making tea. It has very basic controls. You have an on and an off button, and well, [clears throat] when it’s on, then the temperature inside of it rises, and when it’s off, it cools down back to room

02:50:16 - 02:51:12
temperature, which is 20° Celsius. As part of the back end of our project, we provide you with a very basic control scheme for controlling the kettle. You can call kettle on and kettle off, and it turns it on and off. There is also a place in the API where you can make a get request to simply get back the temperature in the correct format Celsius. The network layer of our application is wrapped in the interface kettle service. It provides switch on and switch off functions, which are suspending since you’re just sending a

02:50:44 - 02:51:45
request and probably just waiting for it to complete, and it also contains two non-suspending functions that simply return a flow. Observe temperature returns you a flow of Celsius temperature. Observe kettle power state returns you a flow of kettle power state whether it’s on or off. This might be a great time to go hands-on once more. I am over here in the network kettle service, which is part of the desktop client project. There are two tasks in this file, though for now we will focus on the first one, and that is to create

02:51:15 - 02:52:08
a flow that emits the kettle temperature every second. I’ll give you a few seconds here to pause if you want to make this code change yourself, run the application, and see whether things work as you expect. All right, got something? Well, let’s take a look at how we might approach this. The scaffolding that is provided already gives us a pretty good hint of what this structure should look like. We have a get temperature function that already gives us the temperature from the temperature endpoint. So, we

02:51:41 - 02:52:34
don’t really need to do anything here. We are also already in the context of a cold flow builder. So, effectively what we have here is a flow that just emits a single value, but we want to emit values every second. So, we can simply move the emission into while true and also throw in a delay of 1 second. And that is probably almost everything that we need to do. Let’s run our demo application and see if it is indeed the case. Instead of opening the articles app in the launcher now, I’m just going to open

02:52:08 - 02:53:10
our little kettle app. Like promised, the UI is very bare bones, but let’s turn it on. After turning it on, the temperature does indeed rise and it keeps on rising, hopefully until a safety shut off turns it off at 100° Celsius. We are reaching critical temperature and indeed the temperature starts slowly dropping again. So, we are correctly observing the temperature every second. But there is one thing that seems like it’s still off yet. The buttons for heating up and stopping the heating

02:52:38 - 02:53:32
process don’t seem to update. That’s because we’re not correctly observing the kettle power status yet. If we were, then the UI would expose for us the ability to turn off the kettle. Thankfully, the back end offers a way of observing the kettle in real time using websockets. Web sockets are real-time persistent connections that allow both parties, both server and client, to send and receive messages. And we have a websocket-based endpoint that allows you to observe the power state. Looking at

02:53:06 - 02:54:02
the implementation of observe kettle power state, we can see that most of the plumbing has already been taken care of. It already shows us how a websocket session is opened. It shows us how to get an element from the websocket in the form that it becomes a kettle power state. And well, you can print its state. Once again, I’ll give you a couple of seconds if you want to puzzle this out yourself. Got something? Okay, let’s look at a solution together. For each invocation of this function, the websocket session

02:53:34 - 02:54:34
should only be invoked once, so it certainly shouldn’t go in a loop. However, the receiving and the emitting of the kettle power state should happen in a loop. This is once again an infinite loop. Rather than simply just logging things, we also want to emit whatever we get back, our kettle power state, to whoever is collecting our cold flow. Because receive deserialized already waits for another element to arrive on the web socket, there is no need for us to artificially delay here like we did with the polling

02:54:04 - 02:54:58
implementation for observed temperature. So this looks like a very basic implementation that we might already want to use. Let me open up the kettle again. Clicking the button now, we can see that the state switches and I now have the ability to turn off the kettle, and indeed the temperature lowers itself immediately. What I find particularly cool is that if I create multiple views of the same back end kettle is that they stay in sync. So if I update the state, all other views are immediately changed

02:54:31 - 02:55:33
in real time. It’s pretty neat, right? Now this is a workable first solution, but for extra credit, let’s properly make sure that we close all of the resources as well that we have gotten here. That is as simple as wrapping our entire logic with our loop here in a try block and then in a finally block, making sure that we do indeed actually close the socket session as well. It’s always good to clean up after yourself and not leave any resources dangling. Great, so we have both seen and put into

02:55:02 - 02:56:05
practice some of our first cold flows. But I’m a firm believer that by looking ever so slightly under the hood of what’s going on, we can kind of deepen our understanding. And it will also help us reason about some of the questions that might perhaps come up when we talk about cold flows. So what are actually the moving parts of a flow? There are two parts to the story, flow and flow collector. The flow interface has only a single suspending function called collect, and as its parameter, it takes a flow collector.

02:55:34 - 02:56:36
The flow collector is also an interface with just a single function called emit. Now it might seem a tiny bit counter-intuitive at first, why the flow interface has collect and then the collector interface has emit, but it really is a clever way of coordinating this tandem dance between the collector and the emitter. Because let’s walk through it step by step. Consider the following scenario here. On the right-hand side, I have a very simple flow. It just wants to offer two elements to a collector via emit. On the

02:56:04 - 02:57:11
left-hand side, I invoke collect with println on this specific flow. As we know, the right-hand side here doesn’t do anything on its own. It is just a recipe. So what happens when we call letters.collect? The very first thing that collect does is that it kicks off the logic of whatever you have specified in the lambda that is associated with the flow builder. So the code on the right-hand side starts running. It may do some other things, but it will eventually hit an emit call. And when this emit function is invoked, all it

02:56:37 - 02:57:42
does is run the code that is associated with the lambda that we pass to collect. So for the value A, the lambda with println letter is executed. And it may, of course, do some other work, but eventually the execution will finish. And at that point, control flow moves back to our lambda associated with the flow on the right until it once again hits an emit and once again runs the collect lambda, printing the second letter. I love my hand-drawn arrows, but here is a more formal graphic that shows what’s going

02:57:10 - 02:58:11
on. The entire mechanics of flows result from simply two suspending lambdas calling each other in tandem. First, starting the logic of the builder, and then whenever an emit is invoked, sequentially moving over to the lambda associated with collect before returning the control flow. It is quite simple, but it allows us to make a number of inferences that hopefully clear up our understanding of how cold flows work even more. There are a number of questions to which we now have good answers. For example, why can a

02:57:41 - 02:58:39
non-suspend function return a flow? Well, because we understand that we are effectively just defining a lambda function. And such lambdas really only define a recipe of what should happen once invoked. Nothing that happens inside of the builder, even if it’s doing suspending work, executes when we create the flow in the first place. This also now provides a more formal explanation of what happens when you collect the same flow twice. Well, you run the lambda that defines the flow twice. So, of course, each

02:58:10 - 02:59:08
collector is completely separated. A noteworthy corollary, if we’re looking back, for example, to our web socket example here, is also that if we are opening a socket connection, for example, as part of a cold flow builder or we’re making a network request, then those will also happen whenever this flow is collected. We can now also confidently answer the question of whether the logic in a flow is executed sequentially. Yes, because after all, we only have two suspend functions calling each other. And from our previous

02:58:39 - 02:59:38
discussions, we already know that the body of a suspending function is generally executed sequentially. We also now have an more intuitive reason of why the collect function is defined as a suspend function while invoking collect suspends. Well, because it is the function that is responsible for actually running the flow. And inside of the flow, you may use some sort of suspending operations. And we also understand why the collect lambda is defined as suspend as well. Well, because the meaningful work that you are

02:59:09 - 03:00:08
doing as part of the flow builder may continue on the side of the collector. You might want to write some values to a database, you might want to do some IO, or if you’re using flows for animations, for example, you might want to delay elements. We also now have an intuitive understanding of where a cold flow executes its logic. It depends entirely on the collector. The same way that if you called a plain lambda function, it would be called, well, wherever or in whatever context that you call it, the

02:59:38 - 03:00:34
same occurs to wherever you call collect. There is a small nuance to this, though. The flow’s API does recognize, though, that there might be times where you want to execute flows or part of flows on different dispatches, for example. And we will see the flow on operator later on that allows you to influence exactly this kind of behavior. But for our default model, this still stands. We already have an understanding of why it’s possible, but I also want to actually give you the specific advice of

03:00:06 - 03:01:07
keeping your flow returning functions non-suspend. The idea is that creating a flow should be fast. And of course, you might still want to do some sort of scaffolding, like for example, checking that values are in a specific range or that an operation can even occur. But meaningful suspending work should generally be done inside the builder. If a function is both invoking suspending functions by itself and also returning a flow, that may potentially be an indicator that the function is confused about what its job

03:00:36 - 03:01:44
is. Let’s do some hands-on coding again for a second and move back to our articles application. If you are following along, I am now in the task four progress file. It’s part of the desktop clients articles project. Let’s use our knowledge and practical experience of flows to upgrade our articles app with progressive loading. That means that rather than waiting for a suspending function to create our full collection of articles and then throw them onto the screen all at once, what we want to do is show incoming articles

03:01:10 - 03:02:11
as they load. The flow builder is already present for us, so now we just need to do a little bit of work of wiring things up and emitting at the right time. I’ll give you a few seconds to pause here if you want to attempt this yourself. Got a solution? Okay, let’s take a look. We are familiar with how we get and create these article objects that are also here the return time of the flow. From the service, we grab ourselves the article info list first. And then for each article info in our list, we need to do something. We

03:01:40 - 03:02:50
can first create the article. Here we are using both the article info and also the service get comments for a given article info. And then we need to offer these values to our collector using emit. Having done this, let’s rerun our application. I’ll open up the articles app again and change the loading mode to with progress. Hitting load, we can see that as information trickles in, it is displayed immediately and all articles have arrived. Beautiful. It feels nicely responsive because things pop in as soon as they are

03:02:15 - 03:03:14
available. So there’s a real sense of progress that keeps happening here. But if we are comparing it to our concurrent implementation from prior, we notice that our loading performance has suffered. We are back to 9.1 seconds for loading all of the articles. Well, we shouldn’t be too surprised about this at this point because we understand that our flow is executed sequentially. So if we are getting the comments one after the other for each article, it’s expected that we aren’t as fast as had

03:02:45 - 03:03:45
we tried to do all of those concurrently. That is what you will effectively observe whenever you just use a regular flow. If you are making 50 sequential requests like here, each one of them takes 200 milliseconds, then collecting this flow will take 10 seconds total. Now in the first part of this course, we’ve already equipped you with a number of different tools that allow you to introduce concurrency into your code and you may be tempted to use them in this case as well. Your first thought might be easy. Well, I’ll just

03:03:14 - 03:04:08
use launch. But as we recall, launch is an extension on coroutine scope. But even when we looked inside of how flows are implemented, we saw that there were no coroutine scopes anywhere. The flow collector interface only offers up the emit function. It doesn’t provide you with a coroutine scope. As such, the launch function won’t even resolve. But despite being in a situation where you don’t have a coroutine scope at the ready, you might be tempted to introduce your own coroutine scope. For example,

03:03:42 - 03:04:46
using the coroutine scope builder function. And while this code and type checks, you will get an illegal state exception if you try to run this and it is a helpful error message. It says that the flow invariant is violated. An emission from another coroutine is detected. Flow collector is not threat safe and concurrent emissions are prohibited. Effectively, it tells you nice try, but you are using the wrong API, and it offers helpful advice. To mitigate this restriction, please use channel flow builder instead of flow. So

03:04:14 - 03:05:18
what is this mysterious channel flow then? Well, I’d like to typically think of it as a concurrent flow rather than channel flow because channel flow gives away a little bit of an implementation detail. But effectively, it is a builder that comes with a producer scope, which is a specialized coroutine scope. Instead of using emit, you use send, and send is okay to use concurrently. When you start collecting this flow and the logic that is specified in the associated lambda starts to run, well,

03:04:46 - 03:05:49
new coroutines can be started. And when send is invoked, these values are offered up to the collector. If the collector, which still runs sequentially, isn’t ready yet to process the next element, send will simply suspend. So in order to allow coroutines to be started as part of our flow builder, all we have to do is move from the regular flow builder to channel flow. We also need to make sure that any invocations of emit are replaced with send. The underlying abstraction that also shines through in its name is the

03:05:17 - 03:06:21
channel primitive. In general, a channel can be used to manage multiple producers creating values when there’s only a single consumer. So you can think of the channel as the pipe that puts the values from the producers into a consumable sequence. You may also hear the associated term queue semantics here because effectively those values are being put in some sort of order. This specific behavior is also called fan in. That means that you have multiple producer coroutines that send their results through a channel to a single

03:05:49 - 03:06:48
consumer. Channel flow has a couple of characteristics that make it unique and that can also be customized. The underlying channel that is used to bring all of the information from the different coroutines together uses a default buffer size. The buffer size is 64 elements by default, which means you can store up to those 64 elements before invocations of send start suspending. When the collector kicks off the lambda of a channel flow, the coroutines will run and send elements eagerly, well, either until they’re all processed or

03:06:19 - 03:07:12
until the buffer is full and then suspend. This is a different behavior than what you get from regular flow where you have this tandem operation with one of them waiting on the other. The waiting part only appears once the buffer is full where further send attempts will suspend until buffer space is made available. If you want to customize the buffer size, there’s a special operator that you can chain called .buffer. So now we have a tool of starting coroutines inside of our flows. Let’s put it to

03:06:45 - 03:07:43
practice and speed up our articles app again. Here we are again in IntelliJ, this time in task five, async progress. I’ll give you a couple of seconds if you want to try this implementation yourself. Got something? All right, let’s see. I will start by moving the implementation that we had from task four over here. And I will also add a return here to make sure that this flow is indeed returned from the function. We want to start multiple coroutines to create the individual article objects.

03:07:15 - 03:08:13
To do that, let’s first move to channel flow. We’ll also have to change from emit to send. So far this change hasn’t affected the sequential nature just yet. We still need to start our new coroutines. We want to start one new coroutine per article info, so we’ll do it right here. And we arrive at the following code with a channel flow that launches coroutines which each individually send elements into the channel and expose all of those as a regular flow. Let’s see if this has

03:07:44 - 03:08:42
sped things up a little bit. Going back into the articles app, I am now moving to concurrent with progress as a loading mode. I’ll hit load comments and well, we can see things pop up once again in two seconds. But we still get progressive loading on them. Isn’t that nice? Now it’s fast and progressive. And by the way, all of our implementations are also cancelable out of the box without having to do anything extra. So here, for example, I’ve stopped progress after just a couple of things have been loaded

03:08:12 - 03:09:07
in. So now we’ve seen the two core types of cold flows. We have seen the regular flow builder, which is cold. It executes strictly sequential. It is restricted from launching new coroutines. As such, it runs fully lazily. It is very cheap to create. It has a quite simple and robust interface with just a single function, emit. That’s it. And it has no additional moving parts. Compare this to channel flow, which is also cold, but is specifically designed to be concurrent. It can launch new coroutines, and it

03:08:40 - 03:09:31
just runs them independently, potentially suspending on send. It is not quite as cheap to create as a regular flow because it needs to manage this underlying abstraction of a channel. Its interface is also slightly more complicated. We only looked at the send function, but since there is an entire channel happening, there are also other functions like try, send, and close. And to enable its concurrent functionality, it needs to manage those extra concurrent primitives under the hood. So which flow should you pick?

03:09:05 - 03:10:02
Because it seems that channel flow can just do all the things that a regular cold flow can do, but can do a little bit extra. Well, the general advice is that you should only use channel flow if you need concurrency inside your flow. Otherwise, use just a regular cold flow. By doing so, you use the most simple and robust interface for the job without incurring any extra complexity. By now, we’ve seen cold flows in theory, in action, and under the hood. We have seen that cold flows are inert by default.

03:09:34 - 03:10:31
There are no emissions happening until the collector kicks off everything. The actual running thing is created on demand by the collector. Because of the mechanics, each collector also gets all emissions while because there is one instance of this upstream flow per collector. And we have also seen that some flows, when they have a finite number of elements, can also potentially complete. At that point, the invocation of collect stops suspending and your code keeps on running. But there is another equally

03:10:02 - 03:11:09
important type of flows that we should talk about next, and those are hot flows. Because not all flows in Kotlin coroutines are cold. There are hot flows. And those are a type of flow where you can emit elements even when there are no collectors attached to them. Why are they called hot? Well, because they are always active even when there are no subscribers. You can emit items at any time. As such, they fulfill a slightly different role than cold flows. They’re specifically useful for scenarios where you need to emit events

03:10:35 - 03:11:32
or state changes that are not tied to one particular subscriber. Where with cold flows we were always just talking about the collector, in the context of hot flows we may have more than one such collector. And we also call those subscribers sometimes for that specific reason because they are subscribed to the elements that are emitted from a hot flow. It is also important to note that unlike cold flows, hot flows never complete. This just affects their API surface a little bit. There are two key

03:11:04 - 03:12:09
types of hot flows that we should be aware about. There is shared flow, which is designed for broadcasting values to multiple subscribers. And there is state flow, which is technically a special subtype of shared flow. And its main use is as a state container. So when the subscribers are only interested in the latest value. Now the mechanics that govern hot flows are different, but they are still flows. They still implement the flow interface. You can still use transformation operations like map or

03:11:36 - 03:12:35
filter, as we’ll see later, and you can still simply collect them. Although the semantics here are slightly different, you are effectively subscribing to them. To see a first hot flow in action, let’s build a first shared flow. As a motivating example here, let’s build something that vaguely resembles a number station. If you haven’t heard about number stations before, I encourage you to check out the Wikipedia article. It’s very interesting. They are mysterious radio broadcast stations that

03:12:05 - 03:13:04
seem to send almost arbitrarily random numbers out into the ether. And whoever is listening may be able to decrypt those numbers or maybe not. There’s a lot of speculation going around what number stations are and what they’re used for. That part isn’t really that important. I just needed a slightly better excuse to generate a whole bunch of random numbers again. Let us begin by first looking at the overall setup code that we have here already. I am creating a numbers station component here,

03:12:35 - 03:13:33
which is just a class that has its own scope property so that we can launch new coroutines. I am also already constructing this number station given a parent scope that I’ve obtained by using the coroutine scope builder function. So far, nothing is being emitted, nor is anything being subscribed to. So let’s set that up next. We’ll provide a shared flow as the mechanism for broadcasting. We’ll call it numbers and its public type is shared flow of int. We also need a mutable version of the same shared

03:13:04 - 03:14:15
flow that allows us to actually trigger emissions. This one we typically want to keep private. So let me create a private val _ numbers, which is a mutable shared flow of int. And we simply alias the public variant using get to be the _ numbers value just with a different type. Starting with Kotlin 2.3, there is an even nicer way to express this kind of idiom. So let me just rewrite this code real quick. Rather than creating a separate _ version, I can specify that the mutable variant is simply the associated field

03:13:40 - 03:14:48
of our shared flow, meaning that whenever we use numbers inside of this class, it will be a mutable shared flow, though outside of the class, it will simply appear as the read-only version. Let’s now write a function that starts broadcasting on this. I’ll simply call this function begin broadcasting. It is not a suspending function because in here I will be launching a new coroutine. And this will simply loop forever and emit new values into our numbers shared flow. We still need to generate these, but

03:14:14 - 03:15:17
thankfully there is a helpful get new number function that I already provided myself here. So we’ll throw that one in here as well. This function is a generator that pretends that it is quite slow, so it already delays. So we can simply keep emitting new numbers as we get them. Without even having written any code regarding the collector, we can already see that the usage site of a hot flow generally differs from how we define a cold flow. A hot flow like a mutable shared flow is simply initialized as a variable. And then we

03:14:45 - 03:15:39
effectively have this separate coroutine which we just wrote, which acts as one of the emitters for this mutable shared flow. Because of this structure, we can now have an arbitrary number of coroutines that effectively emit values into our mutable shared flow inside of our number station. So we could start an entire separate generator coroutine and that would work as well. But let’s actually collect something from this shared flow and see what we get back. First we want to make sure that the

03:15:12 - 03:16:07
broadcast is actually running. And already at this point it makes sense to run our code for the first time because we will see that despite nobody listening for the emissions, the generator gets called and new values are emitted into our shared flow. That is precisely what we mean when we say that the flow is hot. Just like a radio station, it doesn’t care whether there’s somebody listening. It is just broadcasting into the ether. But let us tune in and actually receive some of these numbers as a collector or as a

03:15:39 - 03:16:43
subscriber. I’ll start a new coroutine and in here I will just grab the station numbers and I will call collect. You can see that I am using the same API that we have already gotten to know in the context of cold flows. I’m still calling collect, but this time it effectively subscribes me to the shared values that are emitted. Let’s log these numbers. Rerunning the application, we can now see that numbers are generated and also respectively received later on from the subscriber. And out of the box, the

03:16:11 - 03:17:15
default behavior is that a subscriber on a shared flow receives all emissions that happened after it started subscribing. We can see this by adding a delay of 5 seconds, for example, before we start our collector coroutine. Let’s rerun our application. We can see that first a bunch of numbers are generated, but nobody is listening. After 5 seconds, our new coroutine is started and it does indeed receive all those elements from that point. The fact that this is a hot flow also means that different subscribers all share the same

03:16:43 - 03:17:50
values. They all receive the values that are emitted once they start collecting. And if we run this again, nothing surprising should happen. Both A and B get individual values. They aren’t distributed in any way. Each collector gets all emissions from the start of when it subscribes. With this, you can hopefully see that typically a shared flow takes the role of some sort of broadcast bus in your applications. But unlike a radio station, there are a couple of tricks you can do to make sure that subscribers get more than the

03:17:17 - 03:18:15
elements that have just started emitting from when they subscribed. This is what the replay parameter changes. If I were to set a replay of 10, then a new subscriber would get the 10 latest values that occurred before it subscribed, kind of as a jumping off point. We can see this when we rerun the application. Again, our subscribers wait a little bit before they join, but once they do, we can see that we get an entire block of where they are handling the 10 numbers that they got as starting fodder from the replay. Now, looking at

03:17:46 - 03:18:41
this code, you can probably also understand why we say that hot flows generally never complete. The work that is being done to create new elements for a shared flow doesn’t happen inside the shared flow in any way. Instead, we have other coroutines like the one that we defined in begin broadcasting that contribute values to be emitted into the shared flow. If you no longer want those coroutines to emit values into the shared flow, well, you know how to cancel them. And if you wanted to signal

03:18:13 - 03:19:15
to a collector that no more elements will be broadcast on a given shared flow, then you would have to manage this using types. Rather than using plain integer values that are broadcast in your mutable shared flow, you could structure it in a way where it either sends out integers or a special stop marker. For this, you could use for example sealed classes. So we’ve seen some of the key properties of shared flow. A shared flow is active by default. It is created once and it has multiple subscribers. Those subscribers,

03:18:44 - 03:19:41
which are effectively our collectors, get emissions from the start of their subscription. You can specify a replay buffer though to change this behavior. And these shared flows never complete. You manage this part of never completing by either sending a value that indicates a stop or on the production side by simply canceling the coroutines that emit new values into the shared flow. You can see the way that a shared flow was typically declared up here where a private mutable shared flow typically

03:19:13 - 03:20:08
was assigned to an underscored variable and a read-only version without the underscore would just defer to it. With this syntax, you could use the explicit optional downcast protection by calling as shared flow, which wraps the mutable shared flow in a way that prevents people from simply using a cast to get to the mutable version. Though if I may offer a personal opinion on this, I believe that this is something that is best solved on the organizational level and during code reviews. Starting with

03:19:40 - 03:20:41
Kotlin 2.3, the new way that we also saw in the live demo is available. It uses something called the explicit backing field syntax. Here you can express to the compiler that you want the subscribers variable to be exposed as a shared flow externally, but as a mutable shared flow internally as part of the class. Let’s try our hand at a first task that uses the shared flow abstraction. For this exercise, we will be using the basic chat application, which is just a small chat. I can open more than one of

03:20:11 - 03:21:17
those and I want to able to send messages that all chats receive. On the server side, the logic governing this chat is implemented in chatrouting.kt in the server project. As we can see, it exposes a message flow, which is a shared flow of chat messages. It also provides a basic broadcast message function, which emits values into this message flow. If you are interactively following along at home, you can now spend some time to implement the handle socket function. It receives both the WebSocket server session as well as the

03:20:44 - 03:21:38
chat. The behavior that we want to see in the end is that of a regular chat room. That is, when a message is received from the server, it should be broadcast to all participants so they can display it in their user interface. I’ll give you a couple of seconds to pause here if you want to try this by yourself. Got something? Okay, let’s take a look together. The scaffolding already provides us with a coroutine scope and two coroutines that contain helpful hints on how we might want to approach this. We effectively want to

03:21:11 - 03:22:11
have two coroutines collaborating here. One coroutine which takes incoming messages and emits them into our chat’s shared flow, and a second coroutine which collects or subscribes to the shared flow of our chat and then sends out the message to everybody. We want to receive an arbitrary number of messages, so we’ll start with a while true loop. We’ll grab ourselves an individual message by using the socket.receive deserialized with the chat message generic parameter. Now it’s time to emit

03:21:41 - 03:22:39
this into our shared flow. Since the message flow is a read-only from the outside, we need to use the dedicated broadcast message function to invoke this emit. As such, we can just type chat.broadcast message and we’ll broadcast the specific message. So now all incoming messages are emitted into our shared flow. Now it ‘s time to send them back out. We’ll grab ourselves the read-only version of the message flow that’s publicly available and then call collect, that effectively subscribes us.

03:22:10 - 03:23:07
Now we just use the socket.send serialized function and we’ll just put the chat message in here. And for the most basic solution, that’s all we have to do. Let’s restart the application and see it in action. I’ll open up two chat windows here so that we can simulate a conversation, and I’ll write something like hello. And indeed, we can see that both windows receive the message, and this of course also works vice versa. Howdy. That also appears everywhere. And you know, I love coroutines. Amazing.

03:22:38 - 03:23:40
We’ve made it work. Because this uses the same shared flow that we already saw in the number station, we also know that we could, for example, play with replay. Let’s do that for a second. Instead of just having the mutable shared flow be created without any parameters, let’s set a replay of 10 and restart our application. We’ll open up one window and we’ll write something like hello. Anybody there? Still love coroutines. Flows are great, too. Now, if somebody else joins the chat, they too get the

03:23:09 - 03:24:14
messages, up to 10 messages that were buffered and then replayed once this new subscriber appears. Good job, everybody. Now, using this mutable shared flow pattern isn’t the only way that we can create ourselves a hot flow. It is also possible to take a cold flow and convert it into a hot flow using the share in operator. As a parameter, this requires a coroutine scope. From the examples that we’ve seen how a hot flow works, you hopefully have an idea of why that needs to be the case. A cold flow is just an

03:23:42 - 03:24:37
inert recipe that doesn’t do anything by itself. There needs to be a place where the logic that’s specified in the cold flow’s lambda is actually executed. For hot flows, the APIs looked so different that this problem didn’t really occur. We had separate coroutines that did the emissions, but here we naturally get the requirement to figure out where the operation should actually run. You can also provide a parameter called started. There are different values that you can provide here. Sharing started eagerly

03:24:09 - 03:25:06
simply immediately fires off the cold flow and never stops. Sharing started lazily starts when we get the first subscriber. So when the first time somebody calls collect on our hot flow. But once started, those emissions never stop. And then there is while subscribed, which also starts like lazily when the first subscriber appears, but it also stops when the last subscriber disappears. And you can customize it a little bit more, too. Now, as you can probably tell, we ventured far away from two suspending

03:24:38 - 03:25:38
functions calling each other like we did with cold flows. The machinery of hot flows is what automatically manages this subscription style behavior when you call collect. So instead of just executing a lambda here, you subscribe to the flow. Let’s actually put this conversion of a cold flow to a hot flow into practice. For this, we will move back to our kettle application once more. You know the virtual very basic tea kettle. I mentioned before that the temperature that we get back from the API is in the

03:25:07 - 03:26:06
correct format, Celsius. But we may still want to be nice to our Fahrenheit using friends. As such, the kettle view model, which you can find as part of the kettle package in our desktop client, also exposes a Fahrenheit temperature, though it is not implemented yet. Before we make a change here, we can see that the Celsius temperature is simply implemented by calling kettle service dot observe temperature. And looking at the implementation, this is indeed what we wrote beforehand. As this then

03:25:37 - 03:26:40
bubbles up into composed code, it is collected as visual state with some sort of value so that it can be rendered out. But back to the Fahrenheit problem. How might we solve this? Well, the simplest thing we could do would be to simply do the exact same thing as we did with Celsius temperature. We call kettle service and we ask to observe the temperature. This gives us a flow of Celsius temperature. Then we can use an operator, map, and we can convert it. So we can do it dot to Fahrenheit, which we already have provided. And this

03:26:09 - 03:27:04
should technically work just fine. Let’s take a look. I’ll open up my kettle here, and immediately without even turning it on, we can see a bit of a problem. And that is that we are always seeing a pair of loading temperature 20 Celsius. And, of course, changing the power state doesn’t change anything about this. So, while we implemented the feature correctly and we can now see that we have exceeded 100 Fahrenheit, we seem to be making twice the number of requests than really necessary. Let’s

03:26:37 - 03:27:39
fix that. The problem, of course, comes from the fact that we implemented our observed temperature function using a cold flow builder. Since the collector triggers this execution when we have more than one collector, we also have more than one separate execution here. What would be better would be to convert the existing Celsius temperature flow into a hot flow and then modify the information that we get out of that into Fahrenheit. And we can do exactly that using the share in operator. Using sharing on the view model scope

03:27:07 - 03:28:05
and also specifying a started parameter, we can do sharing started. lazily since we’re only interested in the values once somebody actually requests them. Our flow was turned into a hot flow. Now, rather than observing the temperature ourselves, we can simply call Celsius temperature directly. Since this is a nullable, we’ll just add a question mark here. If we wanted to, we could also make the additional small improvement of turning this into a get invocation. Though for our case, this doesn’t make a

03:27:37 - 03:28:38
big difference. Let’s run our application again. Looking at it now, we can see that there is only one request for the temperature per second even though we are showing both Celsius and Fahrenheit. That’s because we managed to successfully share this information using a shared flow. Here’s the same issue again visually. Previously, with only cold flows, each call to collect triggered the entire execution of the flow. That meant when the UI was observing the Celsius flow, it made a network request. And when the UI was

03:28:07 - 03:29:11
observing the Fahrenheit flow, which was just mapping the Celsius flow, well, that also made a separate network request. By turning the Celsius flow shared, we now have one central place where the network request is being made. The Fahrenheit flow transformation only happens on the data that already received. With this, we save, well, 50% of our network requests. Now, shared flow works great, but we can actually still do better because we are actually only interested in the last value of the flow, the state of the kettle. For this

03:28:39 - 03:29:36
specific purpose where we are only interested in the state of something, it is now time to introduce state flow. From an implementation perspective, it really is just a specialized shared flow, but its key properties make it effectively a state container. State flow always contains a value, so when you’re looking at it, you can always be sure there’s something there. In the context of a state flow, emissions also only happen when the value would actually change. This is what we call equality-based conflation. If you were

03:29:07 - 03:30:02
to emit the value three and then the same value three again, well, the state of our container hasn’t really changed. The value is still three. So anybody who’s subscribed to updates on the state flow would not be notified. To help you manage this state, it also comes with a number of specialized functions like update and update and get. These ensure that if you make changes to a state flow concurrently, that things are updated with the correct value. But despite being a subclass of shared flow, it

03:29:35 - 03:30:35
still helps to think of state flow as something generally used for a different purpose because with shared flow, our mental model was that of broadcasting messages, but with state flow, we need to think about it as a state container. State flows represent a single observable value over time. Collectors are still notified of changes by having their collect lambda invoked, but only when the value actually changes. And because of this general property saying it always has a value, it also needs an

03:30:05 - 03:31:06
initial value to be provided in order to be instantiated. Because state flow is simply a state container, we often find that people have an easier time reasoning about it. So it’s perhaps interesting to know that by looking at problems in a different way, oftentimes you can change use cases of shared flow to a use case for state flow. Take for example, our chat abstraction. We started with a shared flow of messages. In our mental model, we had a system to broadcast out messages. We could instead

03:30:35 - 03:31:36
model the state of our chat room instead by storing a list of messages inside of a state flow. Now as new subscribers appear to this state flow based implementation, they will see the entire history of all the messages that have been sent in the state flow. We don’t need to work with things like replay for example. The declaration of state flow follows that of shared flow quite closely. We once again expose a read-only variant of the state flow externally and we keep a mutable variant internally. Because rather than

03:31:06 - 03:32:07
broadcasting we are now updating a state container, we have a slightly different approach to putting new values into our state flow. We use the update function which takes a lambda. In this lambda we get the state so far as the parameter, that’s it here. And then we can make a change, for example add a new message to this collection, to this list of chat messages by just using plus. Under the hood this will simply create a new list of chat messages and put that one into the state flow for observers to see. For

03:31:37 - 03:32:33
many general purpose applications, creating these new lists over and over again is still perfectly fine, especially if you are working with a low number of list elements. But this is a great place to shout out a first party library that we’re building at JetBrains, KotlinX Collections Immutable. It is currently in alpha, so it is not part of the standard library in any way, but it’s still good to take a look at it already. The library provides you with efficient immutable collection types. The library

03:32:05 - 03:33:02
provides you with performant operations to create new collections without the cost of copying all of the elements on each operation. So for example if you have a persistent list and you call add to add a new element, it does return you a new persistent list. However, you did not incur the cost of copying all the original elements in the collection to do so. Talking about how this works under the hood is definitely out of scope, but if you want to learn more about it, the keyword that you should

03:32:33 - 03:33:32
look up for is structural sharing. The move to Kotlin X collections immutable is quite a straightforward one. Rather than using a list, you would use an immutable list of chat messages, and you would instantiate it using the persistent list of constructor. Then when updating, you use an operation like add to create a new collection with that element added. The important point is that you still get a new collection, so things are immutable, but you do so cheaply. Completing the parallels to share in, we also have a way to convert

03:33:02 - 03:33:57
a cold flow into a state flow. Instead of sharing, we simply use state in here. The parameters that you have here available are the same. The only difference is that this one returns you this state container. We can spend a brief moment in the cattle view model to replace sharing using state in. Now we’re using the state container, so we do need to provide an initial value. In our case, we’ll just make this null. Our other code continues working, though if the temperature does not change, no

03:33:30 - 03:34:30
new emissions happen. With our new knowledge of state flows, let’s expand the capabilities of our chat project a little bit as well. I want it to be possible to distinguish between important messages and all other messages. To make this distinction, there is a function called chat message dot is important, which determines whether message is important. For now, that’s just if somebody tags at channel or at here. We already have the state flows that model the list of important chat messages as well as the list of all

03:34:00 - 03:34:59
other chat messages present in this template. What is missing is the logic to ingest chat messages that come in through the chat service and split it up into those two state flows. If you are interactively following along at home, I’ll give you a couple of seconds in case you want to puzzle this out yourself. Got something? Okay, let’s take a look. Inside of the coroutine that we start right here, we want to observe and then split values. The chat service provides us an observe message events function. This one

03:34:29 - 03:35:31
returns a flow chat messages, which we collect. Each invocation gets the new message, and now we just need to determine whether it’s important or not and update our state flows accordingly. If the message is important, then our important messages state flow should be updated. We do this using the update function. It gives us the list of existing chat messages, and we want to append our new message. If the message isn’t important, we want to do the same thing, but instead of updating important

03:35:00 - 03:36:05
messages, we want to update all other messages. Let’s run this and validate that it works using the chat with priorities. A regular message, I love Core Teams, works and is added to messages. A message tagged using at channel lunch in 10 moves to the important messages column. We have successfully updated a state flow. So we have seen our two key types of hot flows. We have the shared flow which is designed for broadcasting events. Here subscribers can come and go, and we also have the state flow.

03:35:33 - 03:36:33
This one represents any kind of state, and it only emits when values change. So between hot and cold, shared and state, when would you use what flow? Well, it is likely that your services would expose cold flows. If you have something like view models in your application, then those likely convert them to shared flows or state flows, and then your UI subscribes to those. Between state and shared flow, my general advice is that if you are not working with broadcasting events specifically, so the classic shared flow

03:36:03 - 03:36:59
use case, then see if you can rephrase your problem into a state flow problem. It often makes it easier to reason and think about. To summarize, hot flows are active by default, which means that they can have emissions with potentially no collectors. Collectors can also be called subscribers because there can be multiple of them. Hot flows are created once, and that instance is then shared between all subscribers. Each collector or each subscriber gets all the emissions starting from the point where

03:36:32 - 03:37:35
they are subscribed. Hot do not have the concept of completion. And even though state flow is a subtype of shared flow, so it shares a bunch of the API surface, their use cases still differ. Comparing hot and cold flows again, we also see their clear differences. Where cold flows are inert by default, hot ones are active. Cold flows are created on demand. Hot ones are only created once. Cold flows only have a single collector. Hot ones have multiple subscribers. With cold flows, the single collector gets all of the emissions.

03:37:03 - 03:38:01
With the hot flow, emissions are shared between all of the subscribers. Cold flows may potentially complete, but hot flows do not. I’m also going to put this flow alignment chart on the screen here for you because it may help you see the relationship between different flows and also their counterparts in regular Kotlin with the general concepts. So that is just an extra resource for you to reference. Now, besides a tiny little bit of mapping, we’ve mainly focused on the results of flows as they come straight

03:37:32 - 03:38:29
out of the flow builder. But of course, there are situations where you might want to transform a flow because you may only be interested in a specific property of a flow. For example, just a couple number of elements. You may only be interested in some of the elements, so filtered by some sort of predicate, maybe uh temporally, all these kind of things. You may also only be interested in a different representation of the object, like Celsius to Fahrenheit, or you might want to have a fusion of multiple flows or separate one flow out

03:38:00 - 03:38:56
into many different ones. And this is where operators come into play. When we talk about flow operators, we generally distinguish between two types, the intermediate flow operators and terminal flow operators. An intermediate operator is any operator that we can apply to a flow and it gets us another flow in return. A terminal operator, on the the other hand, can do things like just collects. So it like runs the actual pipeline of intermediate operators and the upstream flows that we’ve constructed.

03:38:28 - 03:39:18
It may create a collection from values and store the things collected in there, or it might just create an individual value, for example. This differentiation between intermediate operators returning a flow and terminal operators returning something else is something that you may already be familiar with from another concept that’s pretty prevalent in Kotlin sequences. Let’s briefly recall the difference between list operations, which we also describe as eager, and sequence operations, which we describe

03:38:53 - 03:39:56
as lazy. When operating on a list like numbers for example, where we have 1 2 3 4, if we apply a map function and then consecutively a filter function, the entire list will first be transformed using the map and then will be handed off to filter. With sequences, the pipeline of operators that we have is executed for each element. So first we map element one and then we filter element one, we map element two and filter the resulting element four and so on. Flows mirror the behavior of sequences in that individual elements

03:39:24 - 03:40:19
pass through different intermediate operators all the way to the terminal operator. This is the logical fit since we are doing things over time, so we probably want to operate on elements as soon as they become available. So in this example where we have a string flow and we first do some mapping, then some filtering, and then do an operation on each of those elements, we do those element by element. Map, filter, and on each are all intermediate operators, so nothing actually happens until somebody

03:39:51 - 03:40:50
calls collect on this modified string flow. From a terminology perspective, we typically talk about upstream and downstream here to talk about the relation between different intermediate operators. You can kind of think of this as like a multi-stage waterfall where an individual element kind of runs through the entire stream. And we can use this terminology to say for example that map happens upstream of filter or that on each happens downstream of filter. So in brief, intermediate operators return

03:40:21 - 03:41:20
another flow. They are applied to an upstream flow, they return a downstream flow, and they themselves are lazy, so they are only executed once the entire flow has been collected. Once again, by understanding how an intermediate operator is implemented under the hood, we can learn valuable information that allows to make other inferences. The general pattern of operation for an intermediate operator, which you can also see here on the slide with the modify flow operator, is the following. An intermediate operator

03:40:50 - 03:41:50
collects elements from an upstream flow. It does some sort of transformation side effects or some other magic, and then it emits some values into the downstream flow. This is precisely what we see in the code snippet. The modify flow body is wrapped in the flow builder. Inside the flow builder, we call collect. Note that this doesn’t have anything to do with our immediate flow builder. Here, we are collecting from our receiver type. In other words, we are collecting from the upstream flow. So we get an element from our original

03:41:20 - 03:42:20
flow. We do some sort of transformation operation, and then we emit it. And this emission now happens as part of our cold flow builder. Now the built-in operators do a tiny little bit more in order to squeeze out some extra performance, such as operator fusion, but this is a great mental model to think about what happens with intermediate operators because it allows us to understand precisely what happens when we apply an intermediate operator to an arbitrary flow. For example, a hot one. Here we have a function called

03:41:50 - 03:42:53
print urgency that takes a shared flow of text responses as a parameter. We only care about those text responses where the message text starts with urgent, and we want to make it really urgent, so we map it to uppercase. We know that what happens under the hood when we do filter or map is that a new cold flow is created. As such, despite responses being a shared flow, so a flow where emissions can happen at arbitrary times, filter and map aren’t executed by themselves. It is the responsibility of

03:42:21 - 03:43:22
the collector to execute our new flow that had these operators applied to them. And this behavior derives exactly from how the operators are implemented. Let us put this knowledge of how intermediate operators are created to the test, and let’s actually build our own intermediate operator. I’m back in the cattle view model class, which we can find in the kettle project under the desktop client. Scrolling down to the bottom, we can see that there is one more flow that has most of its pipeline

03:42:52 - 03:43:50
commented out, the smooth Celsius temperature. The smooth Celsius temperature flow is supposed to contain average values instead of just the direct readings. And we want to create those using the average of last operator that we have yet to implement. Let’s command click on it and see that it is indeed empty for now. Recall that all intermediate operators pretty much follow the same scheme. They establish their own flow builder. They collect from an upstream flow and they emit into the downstream flow. I’ll give you a

03:43:21 - 03:44:14
couple of seconds here to pause if you want to give implementing average of last a try yourself. Got something? Let’s take a look together. First, we can see that we are already inside of a flow builder, so we don’t need to do anything here. Because we want to compute some averages, we actually need a place to store some state to keep track of the last few samples. For me, I’ll just create a last elements collection. For cases where we are adding elements to one side of a collection and pulling them off the

03:43:48 - 03:44:47
other side, a great choice would be, for example, an array deck. Though you can choose a regular mutable list as well. Make sure this is an array deck of double. Now it’s time for us to collect from the upstream flow. We’ll simply call it collect. Again, the important part to note is that this collect does not happen on our flow builder. Remember that the flow builder only exposes the emit function to us. This collect happens on the upstream flow that we get. In other words, whenever we get a value from the

03:44:17 - 03:45:21
upstream, we get invoked on this lambda. Well, now we just need to add a little bit of logic. We want to add this new element to our last elements. Since we have a constraint of N, which is the number of samples, we want to also make sure that we don’t exceed it. So if our last elements size is greater than N, we will also remove the first element that is in our collection. That way, our collection can grow up to our size of n, but doesn’t exceed it. Lastly, we still need to emit a value to

03:44:50 - 03:45:47
the downstream flow. We can be very straightforward with this and we’ll just grab the last elements and their average. And with that, we have implemented our average of last operator that can be called on arbitrary double flows. Let’s rerun our application and see whether it actually works. Popping up the kettle again, we now see that the smooth temperature field is populated. And clicking the button, we can see that it indeed smoothly rises still, lagging slightly behind the temperature that is

03:45:18 - 03:46:09
actually displayed by the sensor. Well, that’s the effect of the smoothing. Very good. Another little bit of understanding of intermediate operators gained. Most of the operators that you know from working with sequences or collections like filtering and mapping, those all also work when working with flows. So there’s not really a big point in talking about them at length. There is, however, an additional category of flow operators beyond those that are specifically designed for work with

03:45:43 - 03:46:42
flows. So let’s talk about those next. The first subcategory of these kinds of operators are operators that hook into specific flow phases and allow you to execute some logic or emit additional elements at those points. They have relatively straightforward naming convention and semantics, so I don’t want to spend too much time on them. There is, for example, on start with its counterpart for shared flows being on subscription. There is on each, which executes just on each individual element. There is on completion for when

03:46:12 - 03:47:07
a flow completes and on empty for when a flow completes without having emitted any elements. Additionally, there’s also the category of operators that are designed specifically to call emissions. Buffer is the first one in this category and we actually briefly mentioned it when we were talking about channel flow. It buffers elements for consumption for downstream operators and collectors. In other words, it decouples the work of the upstream flow from the downstream flow, buffering elements in the

03:46:40 - 03:47:34
meantime. The debounce operator takes values from a flow and filters out values that are followed by newer values within a certain timeout. This can be useful for implementing features like search while typing based on flows. Conflate is an operator that’s typically used to make sure that the emitter is never waiting for a slow collector. It does that by effectively just throwing away intermediate values. And transform can be thought of as a map function with superpowers. Rather than just taking an

03:47:07 - 03:48:08
individual element and returning a transformed single other element, transform can emit any number, whether that’s zero or just an arbitrary number of values to a downstream for a given input value. The flow on operator changes the context in which a flow is executed. Here the obvious and most important use is changing the dispatcher. And flow on’s behavior is designed to be as predictable as possible. It only affects the preceding operators if they haven’t specified their own context in

03:47:37 - 03:48:45
some way. This is also what we call context preserving. The flow on context does not leak into the downstream flow. So applying flow on only changes the execution logic above where you called flow on. Us curious minds might now wonder what might happen if we had a hot flow, like a mutable state flow, and we called flow on with a separate dispatcher. Recall that after all a hot flow, like a state flow or a shared flow, doesn’t really have any logic attached to it that could be flown on at a different dispatcher.

03:48:12 - 03:49:11
And Column won’t tell us that this makes no sense because applying flow on to a shared flow has no effect. So these were key intermediate operators that were worth discussing in the context of flows. Let’s also have a brief chat about the terminal ones. Like we noted in the beginning, terminal operators may return a value. Some terminal operators, like the two list operator that we can see on the left here, give you a collection of values. You can see that the two list operation itself is actually suspending because it

03:48:41 - 03:49:36
needs to run the entire flow to completion. In the process it runs the entire chain of operators from top to bottom for each element. But not all terminal operators return a value. We have already seen the most basic version of this, the regular collect function with just a lambda where we are doing some sort of meaningful work. But we can also call collect without providing any sort of lambda. In this case, it simply serves as a way to execute the entire upstream flow. So while the return value is unit, we

03:49:09 - 03:50:07
still observe all the side effects. In this case, the individual uppercase and filtered elements are still printed using the on each intermediate operator. So whether you’re creating a list or not really doing anything at all, it’s the terminal operators that trigger the collection of the upstream flow. But let’s briefly return to the topic of infinite flows. How do you go about collecting them? Well, the answer continues to be quite simple. You just use collect. The collect lambda won’t ever stop running

03:49:37 - 03:50:42
by itself, but you can still observe whatever it’s doing as parts of the rest of your system. But what about terminal operators that return a value or a collection? Well, there is two general options here. Either the collector cancels the flow or the collector keeps on collecting. There are certain intermediate operators like take or take while, for example, that simply cancel the upstream flow. So effectively, they act as a conversion function from an infinite flow to a finite flow. Other terminal operators like first or first

03:50:10 - 03:51:15
or null also have this behavior. So in this example, where we have an infinite numbers flow that just creates a bunch of one values, by using the take operator, we convert it to effectively a finite flow. After 10 values have been emitted, the flow is simply canceled. Note that if you were to attempt to collect the entirety of all those infinite numbers into a list, then effectively you would never finish. Any code after attempting to move this to a list would be unreachable. If you want to visually explore some of these flow

03:50:42 - 03:51:45
operators yourself, there is a wonderful community resource called flowmarbles.com. It provides interactive marble diagrams of how individual Kotlin flow operators affect their respective upstream flows. Let’s also briefly talk about how we can control flows in the face of errors and exceptions. The core part of the API that enables you to work with exceptions is the catch operator. We can see it in action here. We have a flow on the left hand side which emits some values before throwing an illegal state exception. The code

03:51:14 - 03:52:11
responsible for collecting this flow first adds a catch operator before it invokes collect. This built-in catch operator receives the exception that was thrown in the flow builder. You can handle it in some way in the lambda which gets it provided as a parameter. For example, you can emit a separate default value. One of the beautiful things about the catch operator is that since it is a build in operator, it itself is aware of cancellation exceptions, so you don’t need to do anything else to support the

03:51:42 - 03:52:39
cancellation case here. Like our other operators, it only concerns itself with the upstream of where we are using catch. Downstream exceptions like the ones that may for example happen inside of your collect block are not caught by any of the preceding catch operators. Though you effectively just need to do a little bit of reshuffling of your logic to get the same effect. Rather than doing your work in the lambda associated with collect, you can move it into an on each operator, then call catch

03:52:11 - 03:53:12
afterwards, and then call collect without any parameters. If you have operations that you want to retry, you can use the retry operator. It retries the collection of the upstream flow when whatever predicate its lambda computes results to true. So we could for example consider the case that we have on the slides here. We have a flow that generates 10 values but has a chance to fail with a certain likelihood with a failed operation exception. By applying the retry operator, we can retry up to five times

03:52:41 - 03:53:40
if our upstream flow failed with a failed operation exception. And this operator is certainly something that our articles app might benefit from. Let’s move back over there for one more time. I am back in our tasks file, This time in task seven retry, which is part of the desktop client. This code is responsible for the unstable with retry loading mode in our application. Let’s first see what this mode looks like out of the box without us making any changes. I’ll change the loading mode to

03:53:11 - 03:54:03
unstable with retry. We can see that the loading status fails. Sometimes it may load an article of two successfully, but then it still fails. We never end up getting all the way. That’s because our backend is throwing 500 internal server errors with a certain probability. By retrying the operation a couple of times, we probably have a better chance of getting all the information that we want to display to our user. The main culprit, of course, is that in get comments with retry, we are using get

03:53:37 - 03:54:35
comments unstable. This specifically hits an endpoint that may simply fail. We can write a small flow-based implementation that retries this individual operation. I’ll give you a couple of seconds here to pause if you want to try this yourself. Got something? Okay, let’s take a look together. Inside of this function, we aren’t working with any flows yet, so let’s create our own. We’ll just create a small a comment flow, and we’ll use the flow builder. Inside, we will simply emit whatever this get

03:54:06 - 03:54:58
comments unstable gives us. We now have packaged our invocation of get comments unstable in a way that allows us to reuse the retry operator because now we have a flow. So we can simply call a comment flow with the retry operator. We can specify a maximum number of retries, let’s say five. Because the signature of this function actually expects us to return a list of the comments that are associated with a single article info object, we still need to make a small transformation here. Well, we actually

03:54:32 - 03:55:26
want to get the first element. Note that we’ve done something slightly different than just retrying the entire operation here. We do have a flow up here that we could have in theory also parameterized using the retry operator. However, that would mean restarting the entire process every single time. Instead, by putting the retry on a single comments unstable, we get a much better chance of actually completing our collection of all the values that we want. Let’s run our application again and see

03:54:59 - 03:55:58
if we fixed it correctly. For unstable with retry, we hit load comments. And indeed, all eight articles have loaded successfully, despite our logs still showing some internal server errors every once in a while. We have retried correctly when we encountered those. Very nice. So we have seen a whole bunch of aspects regarding flow operators. We understand now that most of the operators, both terminal and intermediate, are already known by you from work with sequences. They also simply work in flows. We also

03:55:29 - 03:56:26
now understand that their execution schema is quite similar to sequences. The entire pipeline of operators is executed as each element is emitted. Beyond those operators that you already know, we also have seen some specialized operators that allow you to, for example, hook into its life cycle, control emissions, change the execution context, catch exceptions, or retry. We have also seen that these operators are always context preserving, which means that they always only affect whatever comes before them. They only affect the

03:55:57 - 03:56:54
upstream flow. Putting all of this together, we have seen that flows are an incredibly powerful reactive abstraction that you get out of the box when you’re choosing Kotlin coroutines. And I hope that the overview that you’ve gotten about the different types of flows and their typical use cases is helpful when you apply them yourselves. With that, we have concluded our dive into the world of coroutines and flows. It is the combination of everything that we have learned when talking about cold and hot

03:56:25 - 03:57:19
flows in general, and combining those with these flow operators that makes flows a really, really powerful reactive abstraction to use in your own systems. Thank you for sticking with me all the way to the end here. I hope that you had fun diving into both coroutines and flows with me. And of course, I hope that the things that you have learned throughout this course will be useful as you use coroutines and flows yourself. As you continue your journey with Kotlin coroutines, I can always recommend

03:56:52 - 03:57:49
further deepening your knowledge of what we talked about today by referencing the API documentation of the library itself, as well as our official Kotlin coroutines guide. We want to make sure that the library is as useful as possible for you, so we, of course, always welcome your feedback as well. I hope that you will use coroutines to build many, many more cool things in the future. But for now, it’s time for me to say goodbye, and I hope to see you again in a future video. Have a nice Kotlin. Take

03:57:20 - 03:57:22
care.