Skip to content

Flow: Intermediate operators

Devrath edited this page Dec 27, 2023 · 16 revisions
Intermediate Operators
Map
Filter
Take
  • These operators are executed for every emission of the flow
  • It returns a new and transformed flow

Map

Screenshot 2023-12-27 at 6 24 43β€―PM

Observation

  • 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 to String

Code

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")
                }
            }
}

Output

Received value: -->1
Received value: -->2
Received value: -->3
Received value: -->4
Received value: -->5

Filter

Screenshot 2023-12-27 at 6 27 29β€―PM

Observation

  • Here we pass a collection of items but emit only those that pass a predicate test

Code

        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")
            }
        }

Output

Received value: -->2
Received value: -->4

Take

Clone this wiki locally