Observable

think different reactively.

Observable

Observable
async and event code
handle primitives, events, requests, etc.
.

RxJS library

data streams
broadcasting
listening
.

again: Reactive programming

 

pipe

finalize

of

from 

map

pluck

switchMap

merge

tap

filter

withLatestFrom

 

const obs = of([1, 2, 3])
  .pipe();

const sub = obs.subscribe(result => {
  // do something
});
    
sub.unsubscribe();

Dummy example

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AppService {

  private videos = [];
  
  getVideos(): Observable<any> {
    return of(this.videos);
  }

}

@Injectable

import { Component, OnInit } from '@angular/core';
import { AppService } from '../app.service';

@Component({
  ...
})
export class VideosComponent implements OnInit {

  videos: any[] = [];
  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.getVideos().subscribe(videos => {
      this.videos = videos;
    });
  }
}

@Component

Async pipe. @Component

@Component({
  ...
})
export class VideosComponent implements OnInit {

  videos$: Observable<any>;

  constructor(private appService: AppService) { }

  ngOnInit() {
    this.videos$ = this.appService.getVideos();
  }

}
<ul>

  <li *ngFor="let video of videos$ | async">
  
    ...

  </li>

</ul>

Async pipe. @Component.template

  // INPUT [{data: { ... }}, {data: { ... }}, {data: { ... }}]
  // issue: every object have that annoying *data* field
  //
  // pipe, from, switchMap, pluck, map
  // 
public getData(): Observable<any> {
    return this.apollo.query()
      .pipe(
        switchMap(x => from(x)),
        pluck('data'),
        map((d: any) => {
          // do some work
        })
      );
  }

Bonus

Useful links

Made with Slides.com