Skip to content

Instantly share code, notes, and snippets.

@omkar-tenkale
Created June 3, 2023 10:30
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 omkar-tenkale/507d502f03d1fdd3b8245d576c821fd5 to your computer and use it in GitHub Desktop.
Save omkar-tenkale/507d502f03d1fdd3b8245d576c821fd5 to your computer and use it in GitHub Desktop.
fun launch(block: suspend () -> Unit) {
val callback = object : Continuation<Unit> {
override val context: CoroutineContext = EmptyCoroutineContext
override fun resumeWith(result: Result<Unit>) {}
}
block.createCoroutineUnintercepted(callback).resumeWith(Result.success(Unit))
}
...
downloadButton.setOnClickListener{
launch {
textView.text = "Downloading file"
download("example.com/file.txt", "/sdcard/file.txt")
textView.text = "Download Complete"
}
}
...
suspend fun download(url: String, filePath: String) {
suspendCoroutineUninterceptedOrReturn<Unit> { cont ->
//Download in a background thread
thread {
URL(url).readText().writeTo(File(filePath))
cont.resumeWith(Result.success(Unit))
}
COROUTINE_SUSPENDED
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment