The distinct_until_changed operator

The distinct_until_changed operator filters continuous identical items. It emits only source items that are distinct from the previous item emitted on the source observable. The following is the marble diagram of this operator:

Figure 8.4: The distinct_until_changed operator

Its prototype is the following code:

distinct_until_changed(self, key_selector=None, comparer=None)

This operator accepts two optional parameters:

  • The key_selector parameter is a function used to return the value that must be compared. When no key_selector is provided, then the item itself is used for comparison.
  • The comparer parameter allows you to specify another comparison function than the equality operator.

Here is an example of this operator:

numbers = Observable.from_([1, 2, 2, 2, 3, 2, 1, 1])

numbers.distinct_until_changed().subscribe(
on_next = lambda i: print("on_next {}".format(i)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)

This gives the following results:

on_next 1
on_next 2
on_next 3
on_next 2
on_next 1
on_completed

Any sequence of the same number in the Observable source is translated into a single item being received.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.98.208