Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Building Applications with Scala
Source

Complex Scala with RxScala Observables

package scalabook.rx.chapl

import rx.lang.scala.Observable

object ComplexRxScala extends App {

Observable.

just(1,2,3,4,5,6,7,8,9,10). // 1,2,3,4,5,6,7,8,9,10

filter( x => x%2==0). // 2,4,6,8,10

take(2). // 2,4

reduce(_+_). // 6

subscribe( r => println(s"#1 $r")) val o1 = Observable.

just(1,2,3,4,5,6,7,8,9,10). // 1,2,3,4,5,6,7,8,9,10

filter( x => x%2==0). // 2, 4, 6, 8, 10

take(3). // 2, 4 ,6

map( n => n * n) // 4, 16, 36

val o2 = Observable.

just(1,2,3,4,5,6,7,8,9,10). // 1,2,3,4,5,6,7,8,9,10

filter( x => x%2!=0). // 1, 3, 5, 7, 9

take(3). // 1, 3, 5

map( n => n * n) // 1, 9, 25

val o3 = o1.

merge(o2). // 2,16, 36, 1, 9, 25

subscribe( r => println(s"#2 $r"))

}

The preceding first part of the code creates an Observable with numbers from 1 to 10, and then applies a filter function, which will get only the even numbers. It then reduces them, calculates their sum, and lastly, prints the solution. You can visualize it as depicted in the following image:

For the second part of the code, we create two different observables. The first one is with even numbers and the second one is with odd numbers. These two observables are decoupled from each other; you can control as many observables you want. Later on, the code uses a merge function to join these two observables into a third and new observable containing the content of the first and second observables.

Merging 2 Observables

There are many functions and options, and you can see the whole list at http ://rxmarbies . com/ and https ://github. com/Reactivex/RxScaia. For the sake of simplicity, for now, we are just working with numbers. Later, we will use this to do more advance compositions including database calls and external web services calls.

Summary

In this chapter, we learned the basic concepts of FP, Reactive Programing, and the Scala language. We learned about the basic constructs of the Scala language and Functional Programming, functions, collections, and OO in Scala, and concurrent programming with Futures.

Next, we will see how to use SBT to build Scala projects. We will learn how to compile and run Scala applications using SBT.

2

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Mathematics
Political science
Philosophy
Psychology
Religion
Sociology
Travel