Search code examples
androidandroid-activityandroid-lifecyclecoroutine

Launch coroutine before create the activity Android


I need to do a job before rendering the activity

setContentView

is this example is right, if not what is the best way to lunch coroutine in this case

 override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
    lifecycleScope.launchWhenCreated {
        if (dataStoreRepository.getLanguage() == ARABIC)
            window.decorView.layoutDirection = View.LAYOUT_DIRECTION_RTL
        else
            window.decorView.layoutDirection = View.LAYOUT_DIRECTION_LTR
    }
    super.onCreate(savedInstanceState, persistentState)
}

Solution

  • This is not the best place to perform this action, since you need to block the main thread and it'll probably cause some dropped frames (especially on slower devices).

    Better places to do it:

    • In the application class, before any activities are created (store the layout direction somewhere that can be easily access... shared preferences etc).
    • In the activity immediately proceeding this one (if there was one).

    In both cases, you would ideally show a progress indicator and lock the UI to avoid any dropped frames.