'Emit value of integer when the difference between it and the previous is > 2

I have Flow emit the value of integer and I want to ignore the value when the difference between the current emission and the previous > 2

fun main() {
  GlobalScope.launch(Dispatchers.Main) {
    flowOf(1, 1, 1, 2, 2, 3, 4, 5, 5, 8, 12, 1)
    .distinctUntilChanged{new,old->
     ( new - old) >= 2
    }
   .collect { println(" emitted: $it") }
  }
}

I'm expecting 1,4,8,12



Solution 1:[1]

You used the correct function, but you messed parameters and the return value. Lambda receives old first and new second. This is actually not specified in the documentation. Then you need to return true if items are the same, so the opposite of what you're doing.

A working solution:

.distinctUntilChanged { old, new ->
    new - old <= 2
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 broot