Created
August 13, 2021 09:14
-
-
Save nayan-dhabarde/eefca321b47d7ad884e664dcba264e60 to your computer and use it in GitHub Desktop.
Speak Coroutines with Deferred
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 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 | |
} | |
} |
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 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