Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Kotlin Flow does not have a built-in feature to discard a previous value of the same type when it appears again in the flow. However, you can use operators such as distinctUntilChanged to achieve this.

The distinctUntilChanged operator filters out consecutive elements in the flow that are equal to the previous element. Here's an example:

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

flow
    .distinctUntilChanged()
    .collect { println(it) } // prints 1, 2, 3, 4, 5

In this example, the distinctUntilChanged operator filters out the second occurrence of the value 3 and the second occurrence of the value 4.

You can also provide a custom comparison function to the distinctUntilChanged operator if you need to compare objects by a specific property or criteria.

data class Person(val name: String, val age: Int)

val flow = flowOf(
    Person("Alice", 23),
    Person("Bob", 25),
    Person("Charlie", 23),
    Person("Dave", 25),
    Person("Eve", 23)
)

flow
    .distinctUntilChanged { prev, next -> prev.age == next.age }
    .collect { println(it) }
// prints:
// Person(name=Alice, age=23)
// Person(name=Bob, age=25)
// Person(name=Alice, age=23)
// Person(name=Bob, age=25)
// Person(name=Alice, age=23)

In this example, the distinctUntilChanged operator compares Person objects based on their age property, which allows the operator to filter out consecutive elements with the same age.