Quiero saber un escenario práctico de ambos. Sé la diferencia, pero no pude relacionarme con mi implementación.
Collect recopilará todos los valores y CollectLatest detendrá el trabajo actual para recopilar el valor más reciente.
The crucial difference from collect is that when the original flow emits a new value then the action block for the previous value is cancelled.
flow { emit(1) delay(50) emit(2) }.collect { value -> println("Collecting $value") delay(100) // Emulate work println("$value collected") } prints "Collecting 1, 1 collected, Collecting 2, 2 collected"
flow { emit(1) delay(50) emit(2) }.collectLatest { value -> println("Collecting $value") delay(100) // Emulate work println("$value collected") } prints "Collecting 1, Collecting 2, 2 collected"
Por lo tanto, si cada actualización es importante, como el estado, la vista, las actualizaciones de preferencias, etc., se debe usar la recopilación. Y si algunas actualizaciones se pueden anular sin pérdida, como las actualizaciones de la base de datos, se debe usar collectLatest.