The distinct operators – distinct, distinctUntilChanged

This operator is quite simple; it helps you filter duplicate emissions from the upstream. Take a look at the following example for better understanding:

    fun main(args: Array<String>) { 
      listOf(1,2,2,3,4,5,5,5,6,7,8,9,3,10)//(1) 
        .toObservable()//(2) 
        .distinct()//(3) 
        .subscribe { println("Received $it") }//(4) 
   } 

On comment (1), we created a list of Int containing many duplicate values. On comment (2), we created an Observable instance from that list with the help of the toObservable() method. On comment (3), we used the distinct operator to filter out all duplicate emissions.

Here is the output:

What the distinct operator does is remember all the emissions that took place and filters any such emissions in future.

The distinctUntilChange operator is slightly different. Instead of discarding all duplicate emissions, it discards only consecutive duplicate emissions, keeping the rest at its place. Please, refer to the following code:

    fun main(args: Array<String>) { 
      listOf(1,2,2,3,4,5,5,5,6,7,8,9,3,10)//(1) 
        .toObservable()//(2) 
        .distinctUntilChanged()//(3) 
        .subscribe { println("Received $it") }//(4) 
    } 

Here is the output:

Take a cautious look at the output; item 3 is printed twice, second time after 9. The distinct operator remembers each item until it receives onComplete, but the distinctUntilChanged operator remembers them only until it receives a new item.

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

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