官术网_书友最值得收藏!

The ReactiveEvenOdd program

So, now that we are somewhat familiar with observables, let's modify the even-odd program in a reactive way. Here is the code for doing so:

    fun main(args: Array<String>) { 
      var subject:Subject<Int> = PublishSubject.create() 
 
      subject.map({ isEven(it) }).subscribe({println
("The number is ${(if (it) "Even" else "Odd")}" )}) subject.onNext(4) subject.onNext(9) }

Here is the output:

In this program, we have used subject and map, which we will cover in the later chapters. Here, it is just to show how easy it is in reactive programming to notify the changes. If you look at the program closely, then you'll also find that the code is modular and functional. When we notify subject with a number, it calls the method in map, then it calls the method in subscribe with the return value of the map method. The map method checks if the number is even and returns true or false accordingly; in the subscribe method, we are receiving that value and printing even or odd accordingly. The subject.onNext method is the way through which we message the new value to the subject, so it can process it.

主站蜘蛛池模板: 博兴县| 营山县| 阳高县| 基隆市| 新绛县| 莒南县| 洛隆县| 当雄县| 余姚市| 肇州县| 南阳市| 临邑县| 蚌埠市| 台中市| 鄯善县| 琼海市| 南丹县| 泰宁县| 潜江市| 绍兴市| 大关县| 苗栗县| 长沙县| 泰顺县| 柞水县| 乐清市| 昭觉县| 玉龙| 德保县| 德令哈市| 闵行区| 隆安县| 郴州市| 梁河县| 深圳市| 从化市| 上杭县| 华池县| 略阳县| 涪陵区| 汉中市|