Created
April 21, 2019 14:33
-
-
Save kamaubrian/4135e560b029a247d1cd988d78773d1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
fun main(args: Array<String>) { | |
getAnswerSynchronously() | |
//getAnswerAsynchronously() | |
} | |
suspend fun getIntegerMultiplication(firstNumber: Int, secondNumber: Int): Int { | |
delay(1000) | |
return firstNumber * secondNumber | |
} | |
//Synchronous code | |
// Note the time taken, as the following are calculations are handled one after the other. | |
fun getAnswerSynchronously() = runBlocking { | |
val startTime = System.currentTimeMillis() | |
val set1 = withContext(Dispatchers.Default) { getIntegerMultiplication(10, 20) } | |
val set2 = withContext(Dispatchers.Default) { getIntegerMultiplication(10, 30) } | |
val sum = set1 + set2 | |
println("The sum is ${sum}") | |
val endTime = System.currentTimeMillis() | |
println("Time taken in synchronous code ${endTime - startTime}") | |
} | |
// Note the time taken, as the following are calculations are handled one after the other. | |
fun getAnswerAsynchronously() = runBlocking { | |
val startTime = System.currentTimeMillis() | |
val set1 = async { getIntegerMultiplication(10,20) } | |
val set2 = async { getIntegerMultiplication(10,30) } | |
val sum = set1.await() + set2.await() | |
println("The sum is ${sum}") | |
val endTime = System.currentTimeMillis() | |
println("Time taken in Asynchronous code is ${endTime - startTime}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment