casolorz
casolorz

Reputation: 9564

What scope should I use when calling a suspended function from a Java Activity?

I'm calling a suspend function from Activity written in Java. Right now I'm using EmptyCoroutineContext.INSTANCE as the return of the getContext() method of my Continuation. Is that the right CoroutineContext? will that lead to issues if the suspended function finishes after my Activity has gone away?

Thanks.

Upvotes: 1

Views: 1346

Answers (2)

MrVasilev
MrVasilev

Reputation: 1563

Here is what the Google documentation said about it:

A LifecycleScope is defined for each Lifecycle object. Any coroutine launched in this scope is canceled when the Lifecycle is destroyed. You can access the CoroutineScope of the Lifecycle either via lifecycle.coroutineScope or lifecycleOwner.lifecycleScope properties.

viewLifecycleOwner.lifecycleScope.launch {
        // Your code here
    }

Here the source: https://developer.android.com/topic/libraries/architecture/coroutines

Upvotes: 0

Francesc
Francesc

Reputation: 29320

I can propose an alternate solution. If you can't modify your Activity, you could consider creating a delegate in Kotlin that you offload the calling of that suspending function to. In the delegate you could then access the lifecycleScope of the Activity and use that for the call.

class MyDelegage(private val lifecycleOwner: LifecycleOwner) {

    fun doWorkAsync() {
        lifecycleOwner.lifecycleScope.launch {
            suspendFunHere()
        }
    }
}

then you would instantiate the delegate in your Activity and pass this as the LifecycleOwner.

Upvotes: 3

Related Questions