Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to launch a coroutine on Android?

Tags:

I'm trying to figure out how to launch a coroutine. I want it to call two suspend functions in sequence.

The first docs I read said to do this:

class Something {
  fun initialize() {
    launch {
      suspendFun1()
      suspendFun2()
    }
}

But the launch method was not found by Android Studio. Then I learned that the official coroutine docs suggest using GlobalScope.launch:

class Something {
  fun initialize() {
    GlobalScope.launch {
      suspendFun1()
      suspendFun2()
    }
}

But then I read in this post that you should not use GlobalScope.launch.

So I found another blog post explaining that I need a CoroutineScope to call launch. But it doesn't explain how to build one.

Then I found this blog post explaining how to build one for Activities and ViewModels, by implementing CoroutineScope on the class:

class Something : CoroutineScope {
  private lateinit var job: Job
  override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

  fun initialize() {
    job = Job()
    launch {
      suspendFun1()
      suspendFun2()
    }
}

Then I read this blog post saying I should not implement CoroutineScope

class Something {
  protected val scope = CoroutineScope(
    Job() + Dispatchers.Main
  )

  fun initialize() {
    scope.launch {
      suspendFun1()
      suspendFun2()
    }
}

But I'm not sure I understand the meaning of Job() + Dispatchers.Main, as this seems to work as well:

class Something {
  protected val scope = CoroutineScope(Dispatchers.Main)

  fun initialize() {
    scope.launch {
      suspendFun1()
      suspendFun2()
    }
}

Can someone explain to me simply the best way to do this? Is it as above? I'm sure this has been asked already, so I apologize if this is a duplicate question. But as you can see, there are not clear answers on this. I would like to hear your input.

like image 774
PhillyTheThrilly Avatar asked Nov 26 '19 22:11

PhillyTheThrilly


People also ask

How do I start coroutines on Android?

The simplest way to create a coroutine is by calling the launch builder on a specified scope. It Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as a Job. The coroutine is canceled when the resulting job is canceled. The launch doesn't return any result.

What is coroutine launch?

launch is a coroutine builder. It launches a new coroutine concurrently with the rest of the code, which continues to work independently. That's why Hello has been printed first. delay is a special suspending function.

What is a coroutine Android?

A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages.


1 Answers

Last two solutions are fine. CoroutineScope(context: CoroutineContext) creates an empty Job if you pass a context without one.

Specifying job + dispatcher is just more explicit way to build it as in some cases you might want to use a SupervisorJob instead to prevent entire scope from being canceled when one of child jobs fail.

As for building scopes in Activities and ViewModels instead of declaring your own you can use ones built-in into KTX library by importing KTX fragment module:

// add to your apps dependencies
implementation 'androidx.fragment:fragment-ktx:1.2.0-rc02'

Now inside your Activitys and Fragments you can use lifecycleScope and inside ViewModel a viewModelScope which are scopes backed by SupervisorJob + Dispatchers.Main.immediate and are automatically canceled when their respective lifecycle is destroyed.

like image 62
Pawel Avatar answered Oct 16 '22 22:10

Pawel