repeatOnLifecycle
Runs the given block in a new coroutine when this
Lifecycle is at least at state and suspends the execution until this
Lifecycle is Lifecycle.State.DESTROYED.
The block will cancel and re-launch as the lifecycle moves in and out of the target state.
The best practice is to call this function when the lifecycle is initialized. For example, onCreate
in an Activity, or onViewCreated
in a Fragment. Otherwise, multiple repeating coroutines doing the same could be created and be executed at the same time.
Repeated invocations of block
will run serially, that is they will always wait for the previous invocation to fully finish before re-starting execution as the state moves in and out of the required state.
Warning: Lifecycle.State.INITIALIZED is not allowed in this API. Passing it as a parameter will throw an IllegalArgumentException.
Parameters
Lifecycle.State in which block
runs in a new coroutine. That coroutine will cancel if the lifecycle falls below that state, and will restart if it's in that state again.
The block to run when the lifecycle is at least in state state.
LifecycleOwner's extension function for Lifecycle.repeatOnLifecycle to allow an easier call to the API from LifecycleOwners such as Activities and Fragments.