Skip to content

Instantly share code, notes, and snippets.

@le0nidas
Last active March 28, 2021 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save le0nidas/01663158314aa2f0bd48be3c6d2a86fd to your computer and use it in GitHub Desktop.
Save le0nidas/01663158314aa2f0bd48be3c6d2a86fd to your computer and use it in GitHub Desktop.
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