Created
September 21, 2020 15:54
-
-
Save saldisobi/258a0644b6b5661d67d003c538968c9f 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
class BlankViewModel : ViewModel() { | |
fun testCoroutines() { | |
viewModelScope.launch(Dispatchers.IO) { | |
} | |
runBlocking { | |
launch { | |
} | |
launch { | |
} | |
var one = async { | |
getOne() | |
} | |
var two = async { | |
getTwo() | |
} | |
println("The answer is ${one.await() + two.await()}") | |
} | |
GlobalScope.launch { | |
} | |
} | |
fun main() { | |
val time = measureTimeMillis { | |
// we can initiate async actions outside of a coroutine | |
val one = somethingUsefulOneAsync() | |
val two = somethingUsefulTwoAsync() | |
// but waiting for a result must involve either suspending or blocking. | |
// here we use `runBlocking { ... }` to block the main thread while waiting for the result | |
runBlocking { | |
println("The answer is ${one.await() + two.await()}") | |
} | |
} | |
println("Completed in $time ms") | |
} | |
suspend fun getTwo(): Int { | |
delay(1000L) // pretend we are doing something useful here, too | |
return 2; | |
} | |
suspend fun getOne(): Int { | |
delay(1000L) // pretend we are doing something useful here, too | |
return 0; | |
} | |
fun somethingUsefulOneAsync() = GlobalScope.async { | |
doSomethingUsefulOne() | |
} | |
// The result type of somethingUsefulTwoAsync is Deferred<Int> | |
fun somethingUsefulTwoAsync() = GlobalScope.async { | |
doSomethingUsefulTwo() | |
} | |
suspend fun doSomethingUsefulOne(): Int { | |
delay(1000L) // pretend we are doing something useful here | |
return 13 | |
} | |
suspend fun doSomethingUsefulTwo(): Int { | |
delay(1000L) // pretend we are doing something useful here, too | |
return 29 | |
} | |
suspend fun concurrentSum(): Int = coroutineScope { | |
val one = async { doSomethingUsefulOne() } | |
val two = async { doSomethingUsefulTwo() } | |
one.await() + two.await() | |
} | |
private suspend fun doLongRunningTask() { | |
withContext(Dispatchers.Default) { | |
// your code for doing a long running task | |
// Added delay to simulate | |
delay(5000) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment