Coroutines

Coroutines withContext example

Pinterest LinkedIn Tumblr

In this coroutines withContext example and we’ll see how we can change context easily in Coroutines. We’ll learn different ways to switch coroutine contexts also. In android aspects will see how to can switch the context main thread to another threads. So let’s started.

Uses of withContext

A function that is very commonly used in coroutines is withContext. Basically, withContext is allowed us to easily change context. It means It easily switches between dispatchers.

Suppose in an android application we have some heavy processing that we need to do. So we will do that in the Default Dispatchers then when the outcome completed then we want to switch to the Main Dispatchers in order to publish to display outcome on the UI. So we need a way to easily switch between context and the best way to do that is the withContext function. Because it’s very very lightweight.

Example of withContext

So let take a example see the below code

package com.asyncawaitexamplecoroutine

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        runBlocking {
            launch(Dispatchers.Default) {
                Log.d(TAG,"First context: $coroutineContext")
                // default context
                withContext(Dispatchers.IO) {
                    Log.d(TAG,"Second context: $coroutineContext")
                    // IO context
                }
                Log.d(TAG,"Third context: $coroutineContext")
                // back to default context
            }
        }
    }
}

In this code, first I’m going to launch a coroutine in the default dispatcher. and I’m gonna log coroutineContext. So simply I logging out the context that we have. Then I’m gonna switch dispatchers to IO dispatcher. So using withContext(Dispatchers.IO) I’m gonna log the second context here. So once that is finished, so I’m gonna go back to my first context. So let log the coroutineContext again.

So I’m starting a coroutine in default context then I’m switching to IO and then I’m coming back to original. So let’s go head and run the code and see the output that we get from the LOGCAT.

Output

 D/MainActivity: First context: [StandaloneCoroutine{Active}@45522db, Dispatchers.Default]
 D/MainActivity: Second context: [DispatchedCoroutine{Active}@940c178, Dispatchers.IO]
 D/MainActivity: Third context: [StandaloneCoroutine{Active}@45522db, Dispatchers.Default]

Do we have our first context which is standalone coroutine whatever the name is system has given it. Then we are switching context. so we can that we have different Id(940c178) here.

That mainly I just want to show you the different ID that we get. Here is @45522db, @940c178, @45522db. So when we finish there we’re going back to same context that we have initially.

So basically it’s a very lightweight way to switch between context depending on type of functionality, type of processing that we need to do.

Conclusion

That all, in this blog we have learned coroutines withContext example in Kotlin android.  I hope it’s helpful for you. Keep reading 🙂

Please checkout our recent post Why TypeScript is better than JavaScript

Write A Comment