-
Notifications
You must be signed in to change notification settings - Fork 23
Flow: Intermediate operators
Devrath edited this page Dec 27, 2023
·
16 revisions
These operators are executed for every emission of the flow
It returns a new and transformed flow
- Using the
map-operator
we can convert the form of one type of input into another type - In the example below, We have converted from
integer
toString
private val flowOfIntegers = flowOf(1, 2, 3, 4, 5)
viewModelScope.launch {
flowOfIntegers.map {
it.toString()
}.collect {
if(it is String){
// Use smart cast to check if it is string
println("Received value: -->$it")
}
}
}
Received value: -->1
Received value: -->2
Received value: -->3
Received value: -->4
Received value: -->5
- Here we pass a collection of items but emit only those that pass a predicate test
val flowOfIntegers = flowOf(1, 2, 3, 4, 5)
viewModelScope.launch {
flowOfIntegers.filter {
// We use modulus function to check if the number is divisible by 2
it%2 == 0
}.collect{
println("Received value: -->$it")
}
}
Received value: -->2
Received value: -->4