Skip to content

Instantly share code, notes, and snippets.

@hollygood
Created February 14, 2019 14:42
Show Gist options
  • Save hollygood/4c2110b7a4d49ba3995e66a116e5f138 to your computer and use it in GitHub Desktop.
Save hollygood/4c2110b7a4d49ba3995e66a116e5f138 to your computer and use it in GitHub Desktop.
More about higher order mapping
// Higher order mapping: instead of mapping a plain value like 1 to another value like 10,
// we are going to map a value into an Observable. It's just an Observable like any other,
// but its values are themselves Observables as well, that we can subscribe to separately
// Why Higher-Order Observables?
// Avoiding nested subscriptions
/**
* Observable Concatenation: implement sequential requests
* In order to ensure sequentiality, we need to concatenate the multiple httpPost$ Observables together
* RxJs concatMap Operator
*/
//emits 1,2,3
const sourceOne = of(1, 2, 3);
//emits 4,5,6
const sourceTwo = of(4, 5, 6);
//used as static
const example = concat(sourceOne, sourceTwo);
//output: 1,2,3,4,5,6
const subscribe = example.subscribe(val => console.log(val));
/**
* Observable Merging: implement pararell requests
* merging does not rely on completion
* RxJs mergeMap Operator
*/
// RxJS v6+
import { merge } from 'rxjs/operators';
import { interval } from 'rxjs';
//emit every 2.5 seconds
const first = interval(2500);
//emit every 1 second
const second = interval(1000);
//used as instance method
const example = first.pipe(merge(second));
//output: 0,1,0,2....
const subscribe = example.subscribe(val => console.log(val))
/**
* Observable Swtiching: need cancellation logic
* if a new Observable starts emitting values we are then going to unsubscribe from the previous
* observable, before subscribing to the new Observable.
* Rxjs switchMap
* useful for search typehead
*/
const searchText$: Observable<string> =
fromEvent<any>(this.input.nativeElement, 'keyup')
.pipe(
map(event => event.target.value),
startWith(''),
debounceTime(400)
)
.subscribe(console.log);
/**
* Observable Exhaust: for ignoring new Observables while the current one is still ongoing
* Rxjs exhaustMap
* useful example: save() operation, if user click 'save' multiple times, we ignore it if the request is not complete
*/
fromEvent(this.saveButton.nativeElement, 'click')
.pipe(
exhaustMap(() => this.saveCourse(this.form.value))
)
.subscribe();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment