Created
April 25, 2020 06:52
-
-
Save trunghq3101/7bdff1e69cfe43257901c7b32e2f5f9b to your computer and use it in GitHub Desktop.
Kotlin Coroutine Understanding
This file contains hidden or 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
| /** | |
| * You can edit, run, and share this code. | |
| * play.kotlinlang.org | |
| */ | |
| import kotlinx.coroutines.* | |
| import kotlinx.coroutines.flow.* | |
| import kotlin.system.* | |
| fun test1() { | |
| var time = 0L | |
| runBlocking { | |
| time = measureTimeMillis { | |
| val deferred1 = async { | |
| delay(1000) | |
| println("1") | |
| } | |
| println("2") | |
| deferred1.await() | |
| } | |
| } | |
| println("last $time ms") | |
| } | |
| fun test2() { | |
| var parentTime = 0L | |
| var time = 0L | |
| val parentJob = SupervisorJob() | |
| val parentScope = CoroutineScope(parentJob) | |
| parentTime = measureTimeMillis { | |
| runBlocking { | |
| val job = parentScope.launch { | |
| time = measureTimeMillis { | |
| channelFlow { | |
| launch { | |
| delay(1000) | |
| println("1") | |
| 1 | |
| } | |
| flow { | |
| delay(800) | |
| emit(2) | |
| }.collect { | |
| println("2") | |
| send(it) | |
| } | |
| } | |
| .flowOn(Dispatchers.IO) | |
| .collect { | |
| println(it) | |
| } | |
| } | |
| } | |
| delay(500) | |
| job.cancel() | |
| println("inside scope $time ms") | |
| } | |
| } | |
| println("last $parentTime ms") | |
| } | |
| fun main() { | |
| test2() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment