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

RxJSではじめるリアクティブプログラミング

 RxJSではじめるリアクティブプログラミング

Satoshi Watanabe

February 10, 2018
Tweet

More Decks by Satoshi Watanabe

Other Decks in Programming

Transcript

  1. 例 import { Observable } from 'rxjs'; let value =

    10; Observable.fromEvent(document, 'click') .subscribe( () => { //Success Callback value++; document.getElementById('ret').innerHTML = value.toString(); }, (error) => { // Error Callback console.error(error); }, () => { console.log('complete'); } ) ObserverがSubscribe(購読)することにより データを受け取る データを受け取るコールバックは next/error/completeの3種類
  2. const ob$ = Observable.interval(1000) .take(5); setTimeout(() => { ob$.subscribe( (x)

    => { console.log(x); }, (err) => {console.log(err)}, () => {console.log('complete')} ) }, 3000); 0 1 2 3 4 complete 結果
  3. const ob2$ = Observable.interval(1000) .take(5) .publish(); //publishでHotなObservableを作る ob2$.connect(); //connectでデータを流し始める setTimeout(()

    => { ob2$.subscribe( (x) => { console.log(x); }, (err) => {console.log(err)}, () => {console.log('complete')} ) }, 3000); 2 3 4 complete 結果
  4. 例 Observable.from([1, 2, 3, 4, 5, 6]) .filter(x => x

    % 2 == 0) // 2の倍数でfilter .map(x => x * 100) //100かける .subscribe( (x) => { console.log(x); }, (error) => { // Error Callback console.error(error); }, () => { console.log('complate'); } ); > 200 > 400 > 600 > complate 結果
  5. const i1 = document.getElementById('input1'); const i2 = document.getElementById('input2'); const input1$

    = Observable.fromEvent(i1, "input") .map((x) => { const target = x.target; return target.value !== ''; }); const input2$ = Observable.fromEvent(i2, "input") .map((x) => { const target = x.target; return target.value !== ''; }); Observable.combineLatest(input1$,input2$) .map(([a, b]) => a && b) .distinctUntilChanged() .subscribe((x) => { const button = document.getElementById('button'); if (x) { button.removeAttribute('disabled'); } else { button.setAttribute(‘disabled’, ‘’); } })
  6. const sub$ = new Subject(); sub$.subscribe( (x) => { console.log(x);

    }, (err) => { console.error(err); }, () => { console.log('Complete'); } ) sub$.next(10); //10が表示 sub$.next(20); //20が表示 sub$.complete(); //complete