Nivel 16: recolección consciente del ciclo de vida
lifecycleScope & repeatOnLifecycle
Collecting a `Flow` in a coroutine that keeps running while the screen is in the background wastes resources and can crash. `repeatOnLifecycle` starts/stops collection in sync with the lifecycle.
📚 Explicación
`lifecycleScope` cancels its coroutines when the owner is destroyed, but a long-lived `collect` would still run while the app is backgrounded. `repeatOnLifecycle(STARTED)` restarts the collection each time the screen reaches `STARTED` and cancels it on `STOPPED`, so flows are only collected when visible. In Compose, `collectAsStateWithLifecycle()` wraps this same safe pattern for you.
Nota: La ejecución de código no está disponible para Android/Kotlin en el navegador. Usa Android Studio para ejecutar y probar la app.
import androidx.activity.ComponentActivityimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycleimport kotlinx.coroutines.launchclass FeedActivity : ComponentActivity() {private val viewModel: FeedViewModel by viewModels()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)// lifecycleScope is cancelled when the Activity is destroyed.lifecycleScope.launch {// repeatOnLifecycle STARTS collecting when STARTED,// and CANCELS the block when the screen goes below STARTED.repeatOnLifecycle(Lifecycle.State.STARTED) {viewModel.uiState.collect { state ->render(state)}}}}}// In Compose, the equivalent helper is collectAsStateWithLifecycle():@Composablefun FeedScreen(viewModel: FeedViewModel) {val state by viewModel.uiState.collectAsStateWithLifecycle()FeedContent(state)}