Created
February 28, 2022 04:17
-
-
Save rommansabbir/c4c0291c3f36860d4800d96312d739e3 to your computer and use it in GitHub Desktop.
Kotlin: Convert Async APIs into Sync
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 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