• 11
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

I want to start a coroutine immediately. I have a piece of code:

class SampleActivity : AppCompatActivity(), CoroutineScope {

    private var job: Job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Log.d("SampleActivity", "Before launch")

        launch {
            Log.d("SampleActivity", "Inside coroutine")
        }

        Log.d("SampleActivity", "After launch")
    }
}

The Output is:

Before launch
After launch
Inside coroutine

Is it possible to achieve the output in the following order?

Before launch
Inside coroutine
After launch
      • 2
    • launch { } are fire and forget they return immediately a job, and the coroutine is free to take as long to finished as it needs. If you want to suspend the current thread while some work is done and then continue, then you must already be inside a coroutine this will allow you to suspend the execution while you wait for some result.
      • 1
    • @Choim The screen is blinking in my app when user opens it while data from DB is being loaded. I guess launching a coroutine immediately will fix the problem.
      • 1
    • @Sergey blinking screen must not be caused by coroutines which is not executed immediately. I think of you doing something incorrectly.

Try to launch it with:

launch(Dispatchers.Main.immediate)

More info in this article.

  • 1
Reply Report
      • 1
    • Thanks @Demigod. Dispatchers.Main.immediate is an experimental feature and may be changed in the future, I wonder if there is a production ready feature.
      • 2
    • There's also launch(start = UNDISPATCHED), where you don't have to redeclare the dispatcher you're using. It's "the old way" and marked as experimental as well. This feature doesn't yet have its final form. However, given your input in the comments under the question, this will do nothing to solve your problem because the timing difference is negligible. The only relevant effect of this change is in the guaranteed ordering of actions before the first suspension point (i.e., the execution order of the initial continuation).
    • Thanks @MarkoTopolnik, I will give a try and if it's not working I will consider some other approaches for my case.