android studio 4.1
coroutines are the same as threads, exept better (speed & stability wise)
in the gradle file add
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2"
in dependencies {}
this grimoire will start with 2 of the best code snippets for utilizing the
coroutine jutsu.
as a reminder, to run the main func, just paste it into a kt file, it
should have a run arrow next to the function.
mulan szechuan sauce to make codes faster and taste better:
launch jutsu. this codes runs multi functions in parallal
alter code :
###################################
kotlin android studio handler tick event alternative simpler stronger code :
output :
main thread end
tick
tok
tick
tok
tok
tick
tok
tick
tick
tok
tok
tick
tick
tok
tick
tok
tok
tick
Process finished with exit code 0
##################################################
coroutines are the same as threads, exept better (speed & stability wise)
in the gradle file add
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2"
in dependencies {}
this grimoire will start with 2 of the best code snippets for utilizing the
coroutine jutsu.
as a reminder, to run the main func, just paste it into a kt file, it
should have a run arrow next to the function.
mulan szechuan sauce to make codes faster and taste better:
launch jutsu. this codes runs multi functions in parallal
Code:
fun main()= runBlocking{
var c1:Int=1;
var test = ""
var test2:String = "null"
launch (Dispatchers.Default){ while (c1<5){
c1++;
val deferred1 = async { tic("tick") }
val deferred2 = async { tic("tok") }
test = async { tic("tek") }.await()
test2 = "test ok"
} }.join()
//.join can be omitted for extra speed
println(test)
println("test result : $test2")
println("main thread end")
}
suspend fun tic(startNum: String):String{
delay(1000)
println(startNum)
return "test ok"
}
alter code :
Code:
fun main()= runBlocking{
var c1:Int=1;
var test = ""
var test2:String = "null"
launch (Dispatchers.Default){ while (c1<5){
c1++;
val deferred1 = async { tic("tick") }
val deferred2 = async { tic("tok") }
test = async { tic("tek") }.await()
test2 = "test ok"
} }.invokeOnCompletion { throwable -> println("done") }
//.join can be omitted for extra speed
println(test)
println("test result : $test2")
println("main thread end")
}
suspend fun tic(startNum: String):String{
delay(1000)
println(startNum)
return "test ok"
}
###################################
kotlin android studio handler tick event alternative simpler stronger code :
Code:
fun main()= runBlocking{
var c1:Int=1;
launch (Dispatchers.Default){ while (c1<10){
c1++;
val deferred1 = async { tic("tick") }
val deferred2 = async { tic("tok") }.await()
} }
println("main thread end")
}
suspend fun tic(startNum: String){
delay(1000)
println(startNum)
}
output :
main thread end
tick
tok
tick
tok
tok
tick
tok
tick
tick
tok
tok
tick
tick
tok
tick
tok
tok
tick
Process finished with exit code 0
##################################################