Skip to content

Instantly share code, notes, and snippets.

@nayan-dhabarde
Created August 13, 2021 09:14
Show Gist options
  • Save nayan-dhabarde/eefca321b47d7ad884e664dcba264e60 to your computer and use it in GitHub Desktop.
Save nayan-dhabarde/eefca321b47d7ad884e664dcba264e60 to your computer and use it in GitHub Desktop.
Speak Coroutines with Deferred
class YourOldSyncLibrary {
val imageCompressor = ImageCompressor()
fun compress(): Deferred<String> {
val deferred = CompletableDeferred<String>()
imageCompressor.compress(object: OnCompressListener {
override fun onCompress(filePath: String) {
deferred.complete(filePath)
}
override fun onError(exception: Exception) {
deferred.completeExceptionally(exception)
}
})
return deferred
}
}
class YourViewModel {
private val _compressionPath = MutableLiveData<String>()
val compressionPath: LiveData<String>
get() = _compressionPath
fun compressImage() {
viewModelScope.launch {
withContext(Dispatchers.Default) {
_compressionPath.postValue(compress().await())
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment