Question about adapting callback to suspend api. I...
# coroutines
s
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
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
The documentation isnt really clear on if it can happen or not. I guess you are right though that its more of an error.