Skip to content

Instantly share code, notes, and snippets.

@100nandoo
Created July 7, 2020 03:31
Show Gist options
  • Save 100nandoo/1d02ba2e4b588b238fd7ef9f05e4c31f to your computer and use it in GitHub Desktop.
Save 100nandoo/1d02ba2e4b588b238fd7ef9f05e4c31f to your computer and use it in GitHub Desktop.
// Change the media parameter with your own data class
suspend fun TransferObserver.await(media: Media): Boolean =
suspendCancellableCoroutine { cont ->
this.setTransferListener(object : TransferListener {
override fun onProgressChanged(id: Int, bytesCurrent: Long, bytesTotal: Long) {
val progress = ((bytesCurrent / bytesTotal) * 100).toInt()
media.uploadProgress = progress
media.progressListener?.notifyProgressChanged()
}
override fun onStateChanged(id: Int, state: TransferState?) {
if (state == TransferState.COMPLETED) {
media.isUploaded = true
media.progressListener?.uploadSuccess()
try {
cont.resume(true) { cont.cancel() }
} catch (e: AmazonServiceException) {
cont.resumeWithException(exception = e)
}
}
}
override fun onError(id: Int, ex: java.lang.Exception?) {
ex?.let { cont.resumeWithException(exception = it) }
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment