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

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.

主站蜘蛛池模板: 德令哈市| 顺平县| 肃南| 平舆县| 南投县| 富阳市| 靖安县| 安陆市| 小金县| 凤山县| 凭祥市| 鄢陵县| 松江区| 宣城市| 通化县| 嘉义市| 射洪县| 蕲春县| 突泉县| 八宿县| 桑植县| 洮南市| 阳山县| 德化县| 轮台县| 洛川县| 阳信县| 平利县| 修武县| 吉木萨尔县| 饶平县| 松潘县| 易门县| 都安| 东乌珠穆沁旗| 连南| 忻州市| 高要市| 安宁市| 乳源| 阿拉善右旗|