How to cancel a coroutine inside the coroutine? So...
# coroutines
a
How to cancel a coroutine inside the coroutine? Something like in normal coding, I can do
return
, then the statement after this
return
will not be executed. But what about inside a coroutine? You can’t
return
in a coroutine. Seems the answer is
coroutineContext().cancel()
, But with
Anko
, it said
coroutineContext of type CoroutineContext can't be invoked as a function
g
Could you show some sample code
coroutineContext of type CoroutineContext can’t be invoked as a function
Because
coroutineContext
is not a function, but property, please check docs of kotlinx.coroutines
a
For this, i suppose i just need to introduce real kotlin coroutine rather than the Anko one.
The code is here:
Copy code
private fun handleLogDetails() = launch(UI){

        val result:HttpResponse = bg {
            authHelper.logDetails()
        }.await()

        if (result.error) {
            showErrorDialog(result.errorMessage)
            throw CancellationException()
        }
        
        // do something when no error in result
        // how to return above if I don't want to write if else
        
    }
g
For this, i suppose i just need to introduce real kotlin coroutine rather than the Anko one.
Anko uses “real coroutines”, just update version of kotlinx.coroutines in your project
Just use return instead of Cancellation:
Copy code
if (result.error) {
             showErrorDialog(result.errorMessage)
        return@launch
    }
🎉 1
a
Save my day! Thanks
I use coroutine by adding these:
Copy code
implementation "org.jetbrains.anko:anko-coroutines:$anko_version"
    implementation "org.jetbrains.anko:anko-sdk25-coroutines:$anko_version"
    implementation "org.jetbrains.anko:anko-appcompat-v7-coroutines:$anko_version"
No kotlin coroutine here, is it fine?
g
It’s fine, but you use transitive version of kotlinx.coroutines, I would just remove
org.jetbrains.anko:anko-coroutines
and add
Copy code
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5'
compile 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.22.5'
If you use
bg
or
asReference
just copy them to your project
asReference actually would be helpful for your case, because looks like your blocking network request is non-cancellable to avoid memory leasks
a
Really thanks! 1. For that gradle, could I remove that
anko-sdk25-coroutines
and
anko-appcompat-v7-coroutines
? With just use the two you mentoined? 2. Every time I need to invoke some methods from activity class inside a coroutine, if my API doesn’t support cancellation which is exactly my case. I should use the
asReference()
as a bridge to invoke activity methods to avoid mem leak, right?
g
Yes, you can try, depends which APIs of anko you use. You can keep using them, just update Kotlin.dependency (add them explicitly)