Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coroutines without Flow example
class UploadFilesUsecase() : BaseObservable<UploadFilesUsecase.Listener>() {
interface Listener {
fun onFilesUploaded()
fun onFilesUploadFailed()
}
private val MAX_RETRIES = 3
private val mutex = Mutex()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
fun uploadFiles():Boolean = mutex.tryWithLock {
scope.launch {
repeat(MAX_RETRIES) { retryCount ->
try {
val files = listOf(
async { processAndMergeFilesOfTypeA() },
async { processAndMergeFilesOfTypeB() })
.map { it.await() }
val archive = compressMergedFiles(files)
uploadFileToServer(archive)
notifySuccess()
} catch (t: Throwable) {
//log exception
if (retryCount == MAX_RETRIES - 1) {
notifyFaillure()
}
} finally {
deleteTempDir()
}
}
}
}
private suspend fun uploadFileToServer(archive: File) = suspendCoroutine<Int> { cont ->
HttpManager.uploadFiles(archive,
onDone = { code: Int, body: ByteArray ->
if (code / 100 == 2) {
cont.resume(code)
} else {
cont.resumeWithException(Throwable())
}
},
onFailure = {
cont.resumeWithException(Throwable())
}
)
}
private suspend fun processAndMergeFilesOfTypeA(): File = TODO()
private suspend fun processAndMergeFilesOfTypeB(): File = TODO()
private suspend fun compressMergedFiles(files: List<File>): File = TODO()
private fun deleteTempDir(): Unit = TODO()
private fun notifySuccess() {
MainScope().launch { listeners.forEach { it.onFilesUploaded() } }
}
private fun notifyFaillure() {
MainScope().launch { listeners.forEach { it.onFilesUploadFailed() } }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.