Wednesday, March 17, 2021

RxJS note

 1.

let​ myObs$ = clicksOnButton(myButton);

 $is a convention in the Rx world that indicates that the variable in question is an observable.

Much like a promise, we need to unwrap our observable to access the values it contains. The observable unwrapping method is called subscribe.

The function passed into subscribe is called every time the observable emits a value. 

  myObs$.subscribe(clickEvent => console.log(​'The button was clicked!'​));

2.

tsc stopwatch.ts

Got the below error:

node_modules/rxjs/internal/Observable.d.ts:89:59 - error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.

Need run the below to fix (editing the tsconfig.json doesn't work)

npm i @types/node

3.

delay: delay all events coming through the observable chain

​import​ { interval, of } ​from​ ​'rxjs'​;

import { delay, map, take } from 'rxjs/operators';

of​(​'hello'​, ​'world'​, ​'!'​).pipe(

    delay(5000),

    map(word=>word.split('')

    )

).subscribe(console.log);


​​let​ tenthSecond$ = interval(1000);

​tenthSecond$.pipe(

    map(num=>num/10),

    take(3)

).subscribe(console.log);


4. switchMap

The switchMap operator will create a derived observable (called inner observable) from a source observable and emit those values.

When the source emits a new value, it will create a new inner observable and switch to those values instead. What gets unsubscribed from are the inner observables that get created on the fly, and not the source observable.

5.

// RxJS v6+
import { Subject, BehaviorSubject } from 'rxjs';

const subject = new Subject();
const behaviorSubject = new BehaviorSubject('a');

const subjects = [subject, behaviorSubject];
const log = (subjectType: string) => (e: any) => console.log(`${subjectType}${e}`);

//log equals the below log2
const log2 = (subjectType: string)=>{
  return (e: any)=>{
    console.log(`${subjectType}${e}`);
  }
}

console.clear()
console.log('SUBSCRIBE 1');
subject.subscribe(log2('s1 subject'));
behaviorSubject.subscribe(log2('s1 behaviorSubject'));

No comments:

Post a Comment