Is launch { whenStarted {} } and launchWhenStarted {} exactly the same?

0

Issue

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?

Solution

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

Answered By – avalerio

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More