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 ...

Get Reactive Programming in Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.