Created
June 3, 2023 10:30
-
-
Save omkar-tenkale/507d502f03d1fdd3b8245d576c821fd5 to your computer and use it in GitHub Desktop.
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
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