Let's say we have source Observable of Ints:
val source:Observable[Int]
I would like to create another Observable, producing values whose difference to first appeared value at source is greater than 10:
def detect() = Observable[Int](
subscriber =>
if (!subscriber.isUnsubscribed) {
var start:Option[Int] = None
source.subscribe(
item => {
if (start.isEmpty) {
start = Option(item)
}
else {
start.filter(v => Math.abs(item - v) > 10).foreach {
item => subscriber.onNext(item)
}
}
}
)
subscriber.onCompleted()
}
)
Here I've used var start to hold first value of source Observable.
Is there a way to simplify this code? I don't like this approach with assigning value to a var