Created
May 6, 2020 20:10
-
-
Save ATizik/0431c0313d3d0596de3ce9a0fc82b29f to your computer and use it in GitHub Desktop.
Coroutines without Flow example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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