Skip to content

Instantly share code, notes, and snippets.

@omkar-tenkale
Created June 3, 2023 10:30

Revisions

  1. omkar-tenkale created this gist Jun 3, 2023.
    30 changes: 30 additions & 0 deletions FaultyCoroutineLaunchBuilder.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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
    }
    }