Kotlin Flow Simplified
According to Android documentation, a?flow?is a type that can emit multiple values sequentially. A flow is conceptually a stream of data that can be computed asynchronously and Provides intermediate operators?to modify the stream without consuming values. ( So basically it's an alternate to RxJava. Bye-bye RxJava :) )
Flows?by nature are not lifeCycle aware, unlike LiveData. This makes sense as it is not a part of the android component but a type from kotlin language. However, this can be resolved by responsibly collecting flow values within lifecycleScopes via coroutines and other ways.
?Flow is?declarative/cold: It can only be executed on collection. and?there are hot flows as well?(SharedFlow and Stateflow?). (cold: Stops emission when any collector is not active. Hot: it remains in memory as long as the flow is collected or as long as any other references to it exist from a garbage collection root.)
Flow collection can also be made lifecycle aware using below :
1.?repeatonLifeCycle(LifecycleState.STARTED) or flowWithLifeCycle(LifeCycleState.STARTED)
2. .asLiveData()
Flow Builder
val favoriteRecipe: Flow<List<NigerianRecipe>>
recipesRemoteDataSource.latestRecipes
// Intermediate operation to filter the list of favorite recipes
.map { news -> news.filter { userData.isFavoriteRecipe(it) } }
// Intermediate operation to save the latest news in the cache
.onEach { recipes -> saveInCache(recipes) }
Note:?Here Producer can not emit() the values from different CoroutineContext, It should be emitted through the same coroutine context.
领英推荐
State Flow
class CounterModel
private val _counter = MutableStateFlow(0) // private mutable state flow
val counter = _counter.asStateFlow() // publicly exposed as read-only state flow
fun inc() {
_counter.update { count -> count + 1 } // atomic, safe for concurrent use
}
}
Shared Flow
private val _events = MutableSharedFlow<Event>() // private mutable shared fl
val events = _events.asSharedFlow() // publicly exposed as read-only shared flow
suspend fun produceEvent(event: Event) {
_events.emit(event) // suspends until all subscribers receive it
}
Thanks for reading, if you find this helpful please leave alike. I also appreciate feedbacks