-
Notifications
You must be signed in to change notification settings - Fork 22
About Flow
Devrath edited this page Feb 23, 2024
·
7 revisions
- Flows are mostly coldπ§ in nature.
- Here, The flows won't start until there is a subscriber.
- Whenever a new subscriber is added to the flow, It will get all the data. The flow will start from the beginning and send all the data to the subscriber.
- If there are multiple subscribers, All see all the data from the flow.
- The subscribers are responsible for closing the flow for which it is subscribed. So there is no external control here like the way with channels.
- In channels even if there are known consumers the producers continue sending the data. But if there are no consumers, there won't be emissions.
- Each subscriber has its flow but in channels, all the subscribers share the emissions.
- We need to collect a flow in a co-routine, The co-routine has a
job
reference that is used to handle the coroutine - When we cancel the job, The flow associated with the subscriber is canceled
- As we already know if there are no subscribers the flow will not be in an active state.
- Important to note that in channels when u cancel the Channel all the subscribers are cancelled but in flows, When you cancel a consumer the other consumers might not cancel and continue to execute.
private val input = listOf(1,2,3,4,5,6,7,8,9).asFlow()
private var jobIp : Job? = null
fun stoppingFlowDemoStart() {
jobIp = viewModelScope.launch {
input.collect{
println("CurrentElement -> $it")
delay(1500)
}
}
}
fun invokeCancel(){
jobIp?.let {
it.cancel(cause = CancellationException("Cancelled by the user"))
}
}