https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

spand

11/28/2019, 9:31 AM
Question about adapting callback to suspend api. I have the following code below adapting javascript
FileReader
to suspend. Does this look good? • Should I cancel the continuation when the underlying resource is aborted (ie. by the browser) ? • Is this sequence safe ?
continuation.invokeOnCancellation -> abort() -> onabort -> continuation.cancel()
Copy code
suspend fun Blob.readAsDataUrl2(): String {
    val fileReader = FileReader()
    return suspendCancellableCoroutine { continuation ->
        fileReader.onload = {
            val dataUrl = fileReader.result as String
            continuation.resume(dataUrl)
        }
        fileReader.onerror = {
            continuation.resumeWithException(DomExceptionThrowable(fileReader.error as DOMException))
        }
        fileReader.onabort = {
            continuation.cancel()
        }
        continuation.invokeOnCancellation { fileReader.abort() }

        fileReader.readAsDataURL(this) // <-- Async work starts here
    }
}
e

elizarov

11/28/2019, 10:03 AM
Calling
cancel
from
invokeOnCancellation
whould not do anything. It is already cancelled.
So yes, it is safe.
👍 1
If you don’t have an extrenal source of abort, then you don’t even have to install
fileReader.onabort
. But if you do, then you might considering doing
continuation.resumeWithException(IWasAborted(…))
there to distinguish cases when a coroutine was cancelled and when something else aborted your file reader.
s

spand

11/28/2019, 10:09 AM
The documentation isnt really clear on if it can happen or not. I guess you are right though that its more of an error.
2 Views