Kotlin supervisorScope Tutorial 🎯

beginner
24 min

Kotlin supervisorScope Tutorial 🎯

Welcome to the Kotlin supervisorScope tutorial! This lesson is designed to help you understand one of Kotlin's powerful features for managing concurrent tasks. By the end of this tutorial, you'll be able to write your own concurrent programs using the supervisorScope function.

Let's start with the basics!

What is supervisorScope? 💡

In Kotlin, the supervisorScope function is used to create a new scope that behaves as a "supervisor" for its children jobs. It ensures that if any child job fails, the entire supervisor scope and all its remaining child jobs are canceled. This feature is crucial when dealing with concurrent tasks, as it helps manage errors and prevent unwanted behavior in your program.

Creating a supervisorScope 📝

To create a supervisor scope, you simply call the supervisorScope function and pass a block of code containing your concurrent tasks. Here's a basic example:

kotlin
import kotlinx.coroutines.* fun main() = runBlocking { val supervisorJob = supervisorScope { launch { try { while (true) { println("Task 1") delay(1000) } } catch (e: CancellationException) { println("Task 1 canceled") } } launch { try { while (true) { println("Task 2") delay(2000) } } catch (e: CancellationException) { println("Task 2 canceled") } } } delay(5000) supervisorJob.cancel() }

In this example, we've created a supervisor job that runs two tasks concurrently. If you run this code, you'll see both tasks printing their messages every second. After a delay of 5 seconds, the main function cancels the supervisor job, causing both tasks to be canceled and print "canceled" messages.

Advance Use Cases 📝

Now that you understand the basics, let's look at a more complex example where we use supervisorScope to manage errors in our concurrent tasks:

kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.internal.synchronizedTimeoutOrNull fun fetchData(url: String, timeoutMillis: Long): String? { // Simulate network call with timeout if (synchronizedTimeoutOrNull(timeoutMillis) { try { Thread.sleep(timeoutMillis * 2) return "Data fetched from $url" } catch (e: InterruptedException) { return null } }) { println("Request to $url timed out") return null } return null } fun main() = runBlocking { val supervisorJob = supervisorScope { launch { try { val url1 = "https://example.com" val data1 = fetchData(url1, 1000) if (data1 == null) { println("Failed to fetch data from $url1") } else { println("Fetched data from $url1: $data1") } } catch (e: CancellationException) { println("Task 1 canceled") } } launch { try { val url2 = "https://another-example.com" val data2 = fetchData(url2, 500) if (data2 == null) { println("Failed to fetch data from $url2") } else { println("Fetched data from $url2: $data2") } } catch (e: CancellationException) { println("Task 2 canceled") } } } delay(3000) supervisorJob.cancel() }

In this example, we've created a function fetchData that simulates a network call with a given timeout. We use supervisorScope to manage two concurrent tasks, each attempting to fetch data from a different URL. If either task fails to fetch data within the specified timeout, it prints an error message, but the other task continues running. When the main function cancels the supervisor job after 3 seconds, both tasks are canceled and print "canceled" messages.

Quiz 📝

Quick Quiz
Question 1 of 1

What does the `supervisorScope` function do in Kotlin?

By understanding and using supervisorScope, you'll be able to manage concurrent tasks more effectively in your Kotlin projects. Happy coding! 🤖🚀