Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To divide a Kotlin flow into two separate flows, you can use the split operator. This operator takes a predicate function as a parameter and creates two new flows based on the condition provided.

Here's an example:

val flow = flowOf(1, 2, 3, 4, 5)

val (evenFlow, oddFlow) = flow.split {
    it % 2 == 0
}

evenFlow.collect {
    println("Even number: $it")
}

oddFlow.collect {
    println("Odd number: $it")
}

In the example above, we have a basic flow of numbers from 1 to 5. We then apply the split operator to divide the flow into two separate flows: one for even numbers and one for odd numbers. The it % 2 == 0 predicate function is used to determine which numbers go into which flow.

Once we have the two separate flows, we can use the collect operator to print out the numbers in each flow. In this case, we print out the even numbers in one flow and the odd numbers in the other flow.