Home > Software design >  Is launch { whenStarted {} } and launchWhenStarted {} exactly the same?
Is launch { whenStarted {} } and launchWhenStarted {} exactly the same?

Time:12-26

Is the below exactly the same?

lifecycleScope.launch {
    whenStarted { 
        // Do something
    }
}

and

lifecycleScope.launchWhenStarted {
    // Do something
}

Or they do have some distinct purpose, hence both APIs are provided?

CodePudding user response:

lifecycleScope.launchWhenStarted {
    // Do something
}

Is just short hand for

lifecycleScope.launch {
    whenStarted { 
        // Do something
    }
}

But something you can do is

lifecycleScope.launch {
    //do something here in general
    whenStarted { 
        // Do something onStart
    }
    whenCreated {
        // Do something onCreate
    }
    whenResumed {
        // Do something onResume
    }
}

At the end of the day methods: launchWhenStarted & launchWhenResumed & launchWhenCreated are all on the chopping block. They will be removed in the future according to Android themselves. So I would avoid using them even if it saves you a line or two.

Source: https://developer.android.com/reference/kotlin/androidx/lifecycle/LifecycleCoroutineScope

  • Related