Last active
March 28, 2021 11:38
-
-
Save le0nidas/01663158314aa2f0bd48be3c6d2a86fd 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
fun main(): Unit = runBlocking { | |
val job = launch(Dispatchers.IO) { | |
val tasks = downloadAllTasks() | |
printTasks(tasks) | |
} | |
delay(100) | |
job.cancel() | |
} | |
private suspend fun downloadAllTasks(): List<Task> { | |
return suspendCancellableCoroutine { continuation -> | |
continuation.invokeOnCancellation { print("Cancelled...") } | |
downloadTasks(ContinuationAdapter(continuation)) | |
} | |
} | |
private class ContinuationAdapter( | |
private val continuation: Continuation<List<Task>> | |
) : DownloadCallback { | |
override fun onDownloaded(tasks: List<Task>) { | |
continuation.resume(tasks) | |
} | |
} | |
interface DownloadCallback { | |
fun onDownloaded(tasks: List<Task>) | |
} | |
private fun downloadTasks(callback: DownloadCallback) { | |
println("Downloading...") | |
sleep(150) // simulate network latency | |
val tasks = listOf(Task(1), Task(2), Task(3)) | |
callback.onDownloaded(tasks) | |
} | |
private fun printTasks(tasks: List<Task>) { | |
tasks.forEach { task -> println(task.id) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment