Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RxJS Observables & Angular2 HTTP

RxJS Observables & Angular2 HTTP

Sudipta Sen

March 13, 2017
Tweet

Other Decks in Technology

Transcript

  1. 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
  2. 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?
  3. 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
  4. 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.
  5. 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
  6. WHAT IS A STREAM? A sequence of ongoing events ordered

    in time Emits data, error and signal (e.g. complete)
  7. 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.
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. //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
  18. 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
  19. 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.