Coroutines are a technique to deal with multithreading in Kotlin, learn extra about it from the official docs:
https://kotlinlang.org/docs/coroutines-overview.html
An instance of a Coroutine in Kotlin
val runBlocking = runBlocking {
sleep(5)
delay(1_000L)
launch {
delay(1_100L)
notice("inside launch")
}
notice("exterior launch")
}
Introducing the droop
key phrase
coroutineScopes
have to be in wrapping droop
:
droop enjoyable coroutineFunction(): String {
return coroutineScope {
launch {
println("take a look at")
}
"we return this string"
}
}
runBlocking { println(coroutineFunction()) }
Making Asynchronous API calls utilizing Coroutines
droop enjoyable call2Apis() {
val call1 = async {
delay(1_000L)
println("obtained information from api1 @ ${Instantaneous.now()}")
"some information from api1"
}
val call2 = async P
delay(1_500L)
println("obtained information from api2 @ ${Instantaneous.now()}")
"some information from api2"
}
println(call1.await() + " ${Instantaneous.now()}")
println(call2.await() + " ${Instantaneous.now()}")
}
runBlocking { call2Apis() }
sleep(2)
Sharing states between Coroutines
Merely return a coroutineScope
.
droop enjoyable call2Apis() {
return coroutineScope {
val call1 = async {
delay(1_000L)
println("obtained information from api1 @ ${Instantaneous.now()}")
"some information from api1"
}
val call2 = async P
println(call1.isCompleted) // false
println(call1.await()) // pause and look forward to call1 to finish..
delay(1_500L)
println("obtained information from api2 @ ${Instantaneous.now()}")
"some information from api2"
}
println(call1.await() + " ${Instantaneous.now()}")
println(call2.await() + " ${Instantaneous.now()}")
}
}
runBlocking { call2Apis() }
sleep(2)
Run duties as International Scope
runBlocking {
GlobalScope.launch {
//
}
}