Casting emissions (cast operator)

Think of a situation where you want to cast emissions from the Observable to another data type. Passing a lambda just to cast the emissions doesn't seem like a good idea. The cast operator is here to help in this scenario. Let's take a look:

    fun main(args: Array<String>) { 
      val list = listOf<MyItemInherit>( 
         MyItemInherit(1), 
         MyItemInherit(2), 
         MyItemInherit(3), 
         MyItemInherit(4), 
         MyItemInherit(5), 
         MyItemInherit(6), 
         MyItemInherit(7), 
         MyItemInherit(8), 
         MyItemInherit(9), 
         MyItemInherit(10) 
       )//(1) 
 
       list.toObservable()//(2) 
         .map { it as MyItem }//(3) 
         .subscribe { 
             println(it) 
         } 
 
        println("cast") 
 
        list.toObservable() 
            .cast(MyItem::class.java)//(4) 
            .subscribe { 
                println(it) 
            } 
      } 
 
      open class MyItem(val id:Int) {//(5) 
      override fun toString(): String { 
        return "[MyItem $id]" 
      } 
     } 
 
    class MyItemInherit(id:Int):MyItem(id) {//(6) 
      override fun toString(): String { 
        return "[MyItemInherit $id]" 
      } 
    } 

In this program, we have defined two classes: MyItem and MyItemInherit on comment (5) and (6) respectively. We will be using these two classes to demonstrate the uses of the cast operator. So, on comment (1), we created a list of MyItemInherit; for this program, our approach is to try the same thing, first with the map operator, and then we will do the same with the cast operator. On comment (2), we created an observable with a list, and then, on comment (3), we used the map operator and passed a lambda, where we type-casted the emission to MyItemInherit.

We did the same on comment (4), but, this time with the cast operator. Just look at the simplicity of the code now, it looks a lot cleaner and simpler.

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

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