Slide 1

Slide 1 text

RXJS OBSERVABLES AND ANGULAR2 HTTP SUDIPTA SEN SOFTWARE ENGINEER Red Hat Bangalore, R & D

Slide 2

Slide 2 text

function isUserTooYoung(id, callback) { openDatabase(function(db) { getCollection(db, 'users', function(col) { find(col, {'id': id},function(result) { result.filter(function(user) { callback(user.age < cutoffAge) }) }) }) }) } A Promise from ES6: function isUserTooYoung(id) { return openDatabase(db) .then(getCollection) .then(find.bind(null, {'id': id})) .then(function(user) { return user.age < cutoffAge; }); } Callback hell Promise

Slide 3

Slide 3 text

How do we wrap a socket stream in a promise? How do we cancel a promise? How do we retry to get the data from a promise?

Slide 4

Slide 4 text

WHAT IS REACTIVE PROGRAMMING? Programming paradigm that works with asynchronous data streams Data streams can be created from many things UI events HTTP requests File system Array-like object Memory / Cache

Slide 5

Slide 5 text

REACTIVE EXTENSIONS A library for programming asynchronous programs by using observable sequence. Provides a long list of operators which allow us to map, filter, select, transform, combine and compose observables.

Slide 6

Slide 6 text

CHOOSE YOUR PLATFORM Languages Java: JavaScript: C#: C#(Unity): Scala: Clojure: C++: Groovy: RxJava RxJS Rx.NET UniRx RxScala RxClojure RxCpp RxGroovy JRuby: Kotlin: Swift: PHP: Elixir: Lua: Ruby: Python: RxJRuby RxKotlin RxSwift RxPHP reaxive RxLua Rx.rb RxPY ReactiveX for platforms and frameworks RxNetty RxAndroid RxCocoa

Slide 7

Slide 7 text

WHAT IS A STREAM? A sequence of ongoing events ordered in time Emits data, error and signal (e.g. complete)

Slide 8

Slide 8 text

OBSERVABLE Watch the streams for value, error or complete signals and emits function. Observables can be watched by Observers. Observables can continuously watch a stream. We can interact with data stream as regular array or object. Observers can unsubscribe the observables to stop listening to the observables.

Slide 9

Slide 9 text

CREATING AN OBSERVABLE Rx.Observable.create((observer) => { observer.next('Hello'); observer.next('World'); });

Slide 10

Slide 10 text

let ob1 = Rx.Observable.create((observer) => { observer.next('Hello'); observer.next('World'); }); ob1.subscribe((val) => { console.log(val); }); // "Hello" // "World" HOW TO SUBSCRIBE TO AN OBSERVABLE

Slide 11

Slide 11 text

let ob1 = Rx.Observable.create((observer) => { observer.next('Hello'); observer.error('Oops!'); observer.complete(); }); ob1.subscribe( val => console.log('Success: ' + val), err => console.log('Error: ' + err), () => console.log('Completed') ); // "Success: Hello" // "Error: Oops!" MORE ON SUBSCRIBE

Slide 12

Slide 12 text

let ob1 = Rx.Observable.create((observer) => { observer.next(1); observer.next(2); observer.error('No more numbers found'); }); let ob2 = ob1.catch(err => Rx.Observable.throw('Error1: ' + err)); ob2.subscribe( val => console.log('Success: ' + val), err => console.log('Error2: ' + err) ); // "Success: 1" // "Success: 2" // "Error2: Error1: No more numbers found" ERROR HANDLING

Slide 13

Slide 13 text

let ob1 = Rx.Observable.create((observer) => { observer.next(1); observer.next(2); observer.error('No more numbers found'); }); let ob2 = ob1.retry(1); ob2.subscribe( val => console.log('Success: ' + val), err => console.log('Error2: ' + err) ); // "Success: 1" // "Success: 2" // "Success: 1" // "Success: 2" // "Error2: No more numbers found" RETRY MECHANISM

Slide 14

Slide 14 text

let ob1 = Rx.Observable.create((observer) => { observer.next({status: 200, message: 'All good'}); observer.next({status: 503, message: 'Service not available'}); // observer.next({status: 404, message: 'Not found!'}); }).map((item) => { if (item.status === 503) throw item; if (item.status === 404) throw item; return item; }); let ob2 = ob1.retryWhen((errors) => { return errors.flatMap((err) => { // Retry when the status is 503 if (err.status === 503) { console.log(`Status ${err.status} is retriable!`); return Rx.Observable.timer(2000); } // Else pass on the error console.log(`Status ${err.status} is not retriable!`); return Rx.Observable.throw(err); }).take(1) }); ob2.subscribe( val => console.log('Success: ' + JSON.stringify(val)), err => console.log('Error2: ' + JSON.stringify(err)) ); CONDITIONAL RETRY retryWhen

Slide 15

Slide 15 text

let ob1 = Rx.Observable.create((observer) => { observer.next(1); observer.next(2); }); let ob2 = ob1.map((item) => item + 1); ob2.subscribe((val) => { console.log(val); }); // 2 // 3 HOW TO DEAL WITH MAP

Slide 16

Slide 16 text

const source = Rx.Observable.from([1,2,3,4,5]); const example = source.filter(num => num % 2 === 0); const subscribe = example.subscribe( val => console.log(`Even number: ${val}`) ); // "Even number: 2" // "Even number: 4" filter

Slide 17

Slide 17 text

SOME MORE OPERATORS let ob1 = Rx.Observable.create((observer) => { setTimeout(() => observer.next(2), 1000); setTimeout(() => observer.next(4), 3000); }); let ob2 = Rx.Observable.create((observer) => { setTimeout(() => observer.next(1), 500); setTimeout(() => observer.next(4), 2000); }); const ob3 = Rx.Observable.combineLatest( ob1, ob2 ).subscribe((val) => console.log(val)); // [2, 1] // [2, 4] // [4, 4] combineLates

Slide 18

Slide 18 text

SOME MORE OPERATORS let ob1 = Rx.Observable.create((observer) => { observer.next(1); observer.next(2); observer.complete(); }); let ob2 = Rx.Observable.create((observer) => { observer.next(3); observer.next(4); observer.complete(); }); const ob3 = Rx.Observable.forkJoin( ob1, ob2 ).subscribe((val) => console.log(val)); // [2, 4] forkJoin

Slide 19

Slide 19 text

//emit 'Hello' const source = Rx.Observable.of('Hello'); //map to inner observable and flatten const example = source.switchMap( val => Rx.Observable.of(`${val} World!`) ); //output: 'Hello World!' const subscribe = example.subscribe( val => console.log(val) ); SOME MORE OPERATORS switchMap

Slide 20

Slide 20 text

SOME MORE OPERATORS const source = Rx.Observable.interval(1000).take(10); const example = source .do((val) => console.log(`Before publishing: ${val}`)) .publish(); example.subscribe(val => console.log(`Subscriber One: ${val}`)); example.subscribe(val => console.log(`Subscriber Two: ${val}`)); example.connect(); publish | connectable observable | hot observable

Slide 21

Slide 21 text

OBSERVABLE VS PROMISE Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. However, there are important differences between the two: Observables can define both the setup and teardown aspects of asynchronous behavior. Observables are cancellable. Moreover, Observables can be retried using one of the retry operators provided by the API, such as retry and retryWhen. On the other hand, Promises require the caller to have access to the original function that returned the promise in order to have a retry capability.

Slide 22

Slide 22 text

twitter.com/RedHatNews youtube.com/redhat facebook.com/redhatinc THANK YOU! plus.google.com/+RedHat linkedin.com/company/red-hat