Skip to content

Coroutines: Creating a simple coroutine context

Devrath edited this page Dec 30, 2023 · 1 revision

Observation

  • Here observe even before printing the print statements, it printed the statements outside of it and then the print statements inside of it --> Because the coroutine scope suspended the block, and instead of keeping the thread blocked, it proceeded with execution.
  • Now once the suspended block gets executed the other print statements are printed.
  • If we directly try to access the main thread inside the scope, It will print an error(We need to execute it by switching to the main thread).

Code

    fun createCoroutineScopeDemo() {
        println("Before the scope")
        CoroutineScope(context = prepareContext()).launch {

            val name = coroutineContext[CoroutineName]?.name

            println("$name:-> Before the delay")
            delay(1000)
            println("$name:-> After the delay")
        }
        println("After the scope")
    }

    private fun prepareContext(): CoroutineContext {
        val context = EmptyCoroutineContext
        val name = "MyCoroutine"
        val job = Job()
        val exceptionHandler = CoroutineExceptionHandler{ _ , throwable ->
            println("Error in coroutine: $throwable")
        }
        val dispatcher = Dispatchers.Default

      return (context + job + CoroutineName(name) + dispatcher + exceptionHandler)
    }

Output

Before the scope
After the scope
MyCoroutine:-> Before the delay
MyCoroutine:-> After the delay
Clone this wiki locally