Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin: Convert Async APIs into Sync
class Worker {
/*Async API*/
fun doSomething(listener: Listener, throwError: Boolean) {
when (throwError) {
true -> {
Thread.sleep(3000)
listener.onError(Exception("Just a random exception..."))
}
else -> {
Thread.sleep(3000)
listener.onSuccess("Success")
}
}
}
interface Listener {
fun onSuccess(msg: String)
fun onError(e: Exception)
}
}
/**
* Converting Async API into Sync.
* Here is the magic happens though Kotlin's [suspendCoroutine].
* [suspendCoroutine] return a success state or exception.
*
* @param throwError [Boolean].
*
* @return [String].
*/
suspend fun Worker.doSomethingSync(throwError: Boolean): String {
return suspendCoroutine {
doSomething(object : Worker.Listener {
override fun onSuccess(msg: String) {
it.resume("Success")
}
override fun onError(e: Exception) {
it.resumeWithException(e)
}
}, throwError)
}
}
class Tester {
fun test() {
val worker = Worker()
/*Async Operation*/
/*Callback to get notified regarding the result*/
val listener = object : Worker.Listener {
override fun onSuccess(msg: String) {
println(msg)
}
override fun onError(e: Exception) {
e.printStackTrace()
println(e.message)
}
}
/*Do some work, don't throw exception*/
worker.doSomething(listener, false)
/*Do some work, throw exception*/
worker.doSomething(listener, true)
/*Async to Sync Operation*/
CoroutineScope(Dispatchers.Main).launch {
try {
/*Do some work, don't throw exception*/
println(worker.doSomethingSync(false))
/*Do some work, throw exception*/
println(worker.doSomethingSync(true))
} catch (e: Exception) {
e.printStackTrace()
println(e.message)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment