https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

johannes.lagos

08/23/2017, 7:18 AM
I'm experience that the
await()
on my coroutine doesn't wait to be done before it continue.
g

gildor

08/23/2017, 7:23 AM
Could you please provide an example
👍 2
j

johannes.lagos

08/23/2017, 8:02 AM
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

gildor

08/23/2017, 8:21 AM
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

johannes.lagos

08/23/2017, 8:28 AM
Thanks for the reply.
I will refactor the code.
@gildor how could I lock the coroutine, and wait for the result?
g

gildor

08/23/2017, 11:03 AM
Inside coroutine you can use run{} or async{}.await()
Outside suspended block only runBlocking
j

johannes.lagos

08/23/2017, 11:04 AM
Thx
g

gildor

08/23/2017, 11:05 AM
Any suspend function also suspends (lock free wait) coroutine
And coroutine guides, they are really helpful
11 Views