I'd like to figure out if Kotlin can replace our current way of dealing with asynchronous code. Right now, we use CompletableFutures to handle asynchronous code. Here is an example of a such a method:
public void onBalanceRequest(Client client, String name) {
db.fetchBalance(name)
.thenAccept(balance -> {
client.sendMessage("Your money: " + balance);
});
}
The important point here is that onBalanceRequest is called from the main thread, that must not be blocked. Internally, db.fetchBalance runs asynchronous operations and resolves the future on completion, so the given call is not blocking the main thread.
After reviewing the Kotlin docs regarding coroutines, I had hope that we can do something like JavaScript's async/await. For example, this is what we can do in JavaScript:
async function onBalanceRequest(client, name) {
let balance = await db.fetchBalance(name);
client.sendMessage("Your money: " + balance);
}
Now, I've tried to connect our existing API to a Kotlin project:
private fun onBalanceRequest(client: Client) = runBlocking {
val money = db.fetchBalance(client.name)
client.sendMessage("Your money: $money")
}
suspend fun fetchBalance(player: String): Double? {
var result: Double? = null
GlobalScope.launch {
originalFetchBalance(player).thenAccept {
result = it
}
}.join()
return result
}
However, since I used runBlocking, the execution of onBalanceRequest is blocking the main thread. So I'm aksing you, if I can achieve something similar to async/await with Kotlin.
Thank you.
runBlockingif you didn't want to block in the first place? - RolandrunBlockingis for blocking code...launchis for non-blocking ;-) - RolandrunBlockingwithlaunch, my code won't compile. I don't really understand why, but I thought that it can not be used there? - K. D.