Sorting emissions (sorted operator)

There are some scenarios where you would like to sort the emissions. The sorted operator helps you do that. It will internally collect and reemit all the emissions from the source producer after sorting.

Let's take a look at this example and try to understand this operator better:

     fun main(args: Array<String>) { 
       println("default with integer") 
       listOf(2,6,7,1,3,4,5,8,10,9) 
         .toObservable() 
         .sorted()//(1) 
         .subscribe { println("Received $it") } 
 
      println("default with String") 
      listOf("alpha","gamma","beta","theta") 
         .toObservable() 
         .sorted()//(2) 
         .subscribe { println("Received $it") } 
 
      println("custom sortFunction with integer") 
      listOf(2,6,7,1,3,4,5,8,10,9) 
         .toObservable() 
         .sorted { item1, item2 -> if(item1>item2) -1 else 1 }//(3) 
         .subscribe { println("Received $it") } 
 
      println("custom sortFunction with custom class-object") 
      listOf(MyItem1(2),MyItem1(6), 
         MyItem1(7),MyItem1(1),MyItem1(3), 
         MyItem1(4),MyItem1(5),MyItem1(8), 
         MyItem1(10),MyItem1(9)) 
        .toObservable() 
        .sorted { item1, item2 -> 
if(item1.item<item2.item) -1 else 1 }//(4) .subscribe { println("Received $it") } } data class MyItem1(val item:Int)

Take a look at the output first, and then we will explore the program:

Now, let's explore the program. As we already know, the sorted operator helps sorting emissions; to sort, we need to compare, thus, the sorted operator requires a Comparable instance to compare emitted items and sort them respectively. This operator has two overloads, one with no parameter—it assumes that the producer (here Observable) type will implement Comparable and calls compareTo function, failing which will generate error; the other overload is with a method (lambda) for comparing. On comment (1) and (2), we implemented the sorted operator with a default sort function, that is, it will call the compareTo function from the item instance and will throw error if the datatype doesn't implement Comparable.

On comment (3), we used our own custom sortFunction to sort the integers in descending order.

On comment (4), we used an Observable of type MyItem1, which obviously is a custom class and doesn't implement Comparable, so we passed the sortFunction lambda here as well.

Caution: As we already mentioned, the sorted operator collects all emissions and then sorts them before reemitting them in a sorted order; thus, using this operator can cause significant performance implications. Moreover, while using with large producers, it can cause OutOfMemory Error as well. So, use the sorted operator cautiously, or try to avoid it unless extensively required.
..................Content has been hidden....................

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