Está en la página 1de 25

KOTLIN

FLOWS
REPOSITORY
REPOSITORY
REPOSITORY

LiveData in app's architecture ⛓


KOTLIN FLOWS? 🧐

- Constructed on top of
coroutines
- Reactive programming

"In coroutines, a flow is a type that can emit multiple values sequentially, as
opposed to suspend functions that return only a single value."

"A flow is conceptually a stream of data that can be computed asynchronously."

Kotlin flows on Android - doc ⛓


Kotlin flows intro video 📺
CREAR FLOWS - emit
- Varias libraries típicas ya integran flows, como: DataStore, Retrofit, Room o WorkManager
- También los podemos crear nosotros con flowBuilder

COLD FLOWS
Los flows son lazy, creados
on-demand cuando
comenzas a colectarlos.
COLLECT FLOWS - LiveData
- Flows tiene una integración con LiveData, por lo que al llegar al ViewModel uno puede
convertir el flow a live data y usarlo como ya sabemos.
COLLECT FLOWS - collect
- La idea no está muy alejada de como observamos live data. A los flows les hacemos
collect. La forma para esto es:

- Launch en un scope
- Hay que usar
repeatOnLifecycle
- Lifecycle.State.STARTED
- Para menos verborragia en
cada collect se puede armar
alguna extension y/o dentro
de repeatOnLifecycle poner
varios launch
Preguntas hasta ahora?
StateFlow
- "State-holder observable flow that emits the current and new state
to its collectors".

- El state actual se puede leer mediante la property .value

- Para actualizar el state podemos usar MutableStateFlow

- Es un hot flow: "collecting from the flow doesn't trigger any


producer code"

- Cuando le damos collect a un StateFlow recibimos el último state


y los subsecuentes cuando este cambie. (Similar a LiveData!)

- Convertir un flow a StateFlow: .stateIn

StateFlow docs
Migrating from LiveData to Kotlins Flow
-> Configuring the exposed StateFlow (stateIn operator)
.asLiveData()
Transformaciones
Podemos realizar varias
transformaciones en el medio,
recomiendo ver los kotlin docs combine(flow1, flow2, …) {...}
para el flow package

.catch {...}

.map {...}

.filter {...}

.map {...}
flowOn
- Ejecutar en distintos CoroutineContexts .IO
- Cambia el contexto al upstream flow (above)

.flowOn(Dispatchers.IO)

.Default

.flowOn(Dispatchers.Default)

.Main
SharedFlow
- También es un hot flow.

- Convertir un flow a SharedFlow: .shareIn

- Como en StateFlow, también tenemos MutableSharedFlow

SharedFlow docs
Reemplazo para SingleLiveEvent

Otra alternativa: Channel


Algunos links

- Kotlin flows docs

- StateFlow and SharedFlow docs

- Flows intro video

- Migrating from LiveData to Kotlin’s Flow - Medium

- Things to know about Flow’s shareIn and stateIn operators -


Medium

- DataStore (a new SharedPreferences)

- Flows devexperto (tiene también Channel, callbackFlow)


PREGUNTAS
FIN

También podría gustarte