Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

community creator
concurrency
coroutine
kotlin
communitycreator

Coroutine builders & launching coroutines in Kotlin

Adora Nwodo

Coroutine builders

Coroutine builders are functions that help us create a coroutine. They can be called from normal functions because they do not suspend themselves. Three coroutine builders are listed below.

  • launch: start a coroutine in the background and keep working.
  • async: perform an asynchronous operation and return a deferred object which is the equivalent of a JavaScript promise. We can call await on the deferred value in order to wait and get the result.
  • runBlocking: this blocks the current thread and waits for the coroutine to finish execution.

Launching Coroutines

Coroutines are launched in coroutine builders and are bound by a coroutine scope. A lazy way to launch a coroutine would be to use the GlobalScope. This means that the coroutine would be running for as long as the application is running and, if there is no important reason to do this, I believe that it’s a way to wrongly use resources.

In launching coroutines, we would use the launch keyword like so:

...
GlobalScope.launch{
    doSomething() // does some heavy computation in the background
    ... do other stuff
}
...

suspend fun doSomething(){
   // heavy computation here
}

However, as stated earlier, we don’t want to launch coroutines in the GlobalScope. When launching a coroutine, we want to be sure that we do it right so that we can avoid coroutine leaks that will cause us to run out of memory.

In my opinion, launching coroutines in GlobalScope, and forgetting to keep a reference so that we can manually cancel later, could be as error-prone as using callbacks. How do we solve this problem? That’s where structured concurrency comes in.

RELATED TAGS

community creator
concurrency
coroutine
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring