In this tutorial on What are Coroutines in Kotlin, you will learn the basics of threads and understand how coroutines work in Kotlin. You'll look at the different features and examples of coroutines. Finally, you'll see a demo of Kotlin Coroutines.
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
What Are Coroutines In Kotlin?
1.
2. Basics of Coroutines
Examples of Coroutines
Features of Coroutines
What are Coroutines?
What are Threads?
What’s in it for you?
3. What are Threads?
The programs are set of instructions
When a program runs, a process is created which
contains threads.
Program or Set of
instructions
Runs
Process
• Memory
• Process id
• Threads
4. What are Threads?
Threads work in a sequential manner.
Whenever a thread gets stuck while running an
instruction, then the other thread executes the rest
of the instructions
Instruction 3
Process
Instruction 1
Instruction 2
2nd
thread
1st
Thread
Got stuck
5. Coroutines are light weight threads that helps to
write simplified asynchronous code that keeps the
application responsive while maintaining heavy
tasks like network calls
What are Coroutines?
8. Example of Coroutine
fun main() = runBlocking {
launch {
delay(2000L)
println("Sam")
}
print("My name is ")
}
Blocks the thread which is running, until
the code inside is completed
Launches a new coroutine
concurrently that works
independently
Suspending or delaying the
coroutine for a specific time
Output : My name is Sam
9. Basics of Coroutine
Scope builder
The Coroutine Scope is used to declare your own scope. Unlike
suspends and releases the threads underlying
Explicit Job
A Job object is returned by the Launch Coroutine builder, whose tasks is
to explicitly wait for the child coroutines completion. Jobs acts as a handle
to the coroutine in the queue
Suspending functions
Suspending functions are those functions that can be paused and
then continued later, they can be used inside the coroutines and can
use other suspending functions as well.
10. Global scope of
coroutine launched
Suspend function Delay of
2 seconds(will not block
the main thread)
Here the suspend function
delay is used under
runblocking