Last active
December 5, 2023 19:56
-
-
Save af2905/ddf936131120e0f75699091ce8d8a865 to your computer and use it in GitHub Desktop.
functions_work_in_different_threads
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
internal suspend fun downloadUserData(): String { | |
withContext(Dispatchers.IO) { | |
println("downloadUserData started on ${Thread.currentThread().name}") | |
val result1 = async { receiveAdditionalUserData(taskNumber = 1) } | |
val result2 = async { receiveAdditionalUserData(taskNumber = 2) } | |
println(result1.await()) | |
println(result2.await()) | |
// Long asynchronous work is performed here. | |
println("downloadUserData finished on ${Thread.currentThread().name}") | |
} | |
return "User data downloaded" | |
} | |
private suspend fun receiveAdditionalUserData(taskNumber: Int): String = | |
suspendCoroutine { continuation -> | |
println("receiveAdditionalUserData number: $taskNumber started on ${Thread.currentThread().name}") | |
thread { | |
println("downloadAdditionalUserData number: $taskNumber, background work on ${Thread.currentThread().name}") | |
// Long asynchronous work is performed here. | |
continuation.resume("AdditionalUserData $taskNumber received") | |
} | |
println("receiveAdditionalUserData number: $taskNumber finished on ${Thread.currentThread().name}") | |
} | |
internal suspend fun downloadUserAvatar(): String { | |
withContext(Dispatchers.IO) { | |
println("downloadUserAvatar started on ${Thread.currentThread().name}") | |
// Long asynchronous work is performed here. | |
println("downloadUserAvatar finished on ${Thread.currentThread().name}") | |
} | |
return "Avatar downloaded" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment