I'm experience that the `await()` on my coroutine ...
# coroutines
j
I'm experience that the
await()
on my coroutine doesn't wait to be done before it continue.
g
Could you please provide an example
👍 2
j
This is my coroutine method:
Copy code
suspend  fun ServiceHelper.getList(): ListOfWishes {

return suspendCancellableCoroutine { continuation ->

    getAllLists(object : ResponseReceiver<ListOfWishes> {
        override fun onResponse(response: Response<ListOfWishes>?) {
            continuation.resume(response?.data!!)

        }

        override fun onError(response: Response<ErrorList>?) {
            val throwable = Throwable(Util.getFirstErrorSafe(response?.data))
            continuation.resumeWithException(throwable)
        }
    }, RequestUtils.generateUniqueRequestId(), false, null, object : OnRequestListener {
        override fun beforeRequest() {}
        override fun afterRequestBeforeResponse() {}
        override fun afterRequest(isDataSynced: Boolean) {}
    })
}
}
Copy code
suspend fun ServiceHelper.wishLists(): Deferred<ListOfWishes> {
return async(CommonPool){
    getWishList()
   }
}
Copy code
fun getUpdatedLists(): ListOfWishes?{
    val context = Injector.getContext()
    val serviceHelper = Util.getContentServiceHelper(context) 
    var list = ListOfWishLists()
    launch(Android){
        try {
            list = serviceHelper.wishLists().await()
        }catch (ex: Exception){
            Timber.d("Error: $ex")
        }
    }
    return list
Important to mention that
getUpdatedList
is my interop method with old java legacy code
If I set
fun getUpdatedList(): ListOfWishes? = runBlocking{}
I experience that it will block the main thread, and the coroutine never reach
continuation.resume()
g
But you cannot use it this way
getUpdatedList is async, you cannot get result without blocking here
also you use launch in wrong way. Launch means start and forget and don’t lock even inside another coroutine, you cannot use it as closure to asign variable (you can but it will not work correctly)
👍 2
to use this code in java you should return some callback for Java, to allow use non blocking API
for example you can return lambda, as simplest (no error handling) callback
j
Thanks for the reply.
I will refactor the code.
@gildor how could I lock the coroutine, and wait for the result?
g
Inside coroutine you can use run{} or async{}.await()
Outside suspended block only runBlocking
j
Thx
g
Any suspend function also suspends (lock free wait) coroutine
And coroutine guides, they are really helpful