I am experimenting with the new coroutines and trying to incorporate them into an existing project with some ugly AndroidNetworking api requests.
So my current api requests are using callbacks like this...
fun getSomethingFromBackend(callback: (response: JSONArray?, error: String?) -> Unit) {
AndroidNetworking.get(...).build().getAsJSONObject(object : JSONObjectRequestListener {
override fun onResponse(response: JSONObject) { ... }
override fun onError(error: ANError) { ... }
}
}
And now I am trying to incorporate coroutines like this...
fun someFunction() = runBlocking {
async { callGetSomething() }.await()
}
suspend fun callGetSomething(): JSONObject? = suspendCoroutine {
Something().getSomethingFromBackend {something
...
it.resume(something)
}
}
As you can see, I am trying to run the callGetSomething in a coroutine and once there, suspend the coroutine until the async API returns.
My problem is, it never returns. Even if I debug in the onResponse, onError, etc, it never get back from the backend.
But if I remove the = suspendCoroutine it works, at least it returns, but the await will not work off corse, because the execution will just continue.
How can I solve this so the await() actually waits for the async call callback?
Thanks a lot!