Skip to content

Instantly share code, notes, and snippets.

@dkellycollins
Created May 7, 2020 18:55
Show Gist options
  • Save dkellycollins/c03e15bacbbe578a235279f7b2973790 to your computer and use it in GitHub Desktop.
Save dkellycollins/c03e15bacbbe578a235279f7b2973790 to your computer and use it in GitHub Desktop.
* Promise vs Observable
* Promise
* Single async event that can either complete or fail once.
* Can be used with async/await keywords.
* Observable
* Can emit multiple events async.
* Offers a bit more control over the async task, for example cancelling.
* Cannot be used with async/await keywords.
* Think of Observables as a stream of data instead of an async task.
* Observable is the default used in Angular, but promises are still fine to use.
* You can convert an Observable into a promise by calling toPromise.
* Hot vs Cold
* Just know that Cold observables will not emit events until something has subscribed to them.
* All Observables returned from httpClient are cold.
* subscriptions vs the async pipe
* Generally using the async pipe is prefered over managing subscriptions
* Subscription can introduce memory leaks if not managed properly.
* If you must use a subscription, unsubscribe from it in ngOnDestroy.
* Piping
* switchMap
* "switches" to a new observable
* Useful when one observable requires input from another
* map
* simply maps the data to a new structure.
* startWith
* Emits the provided data before anything else in the observable.
* Useful when your observable represents state, and you need an initial value for the ui.
* shareReplay
* "replays" the last x number of events when something subsscribes to the observable.
* Useful for when you use a single observable in multiple places in your template.
* tap
* Runs the provided function for each event, but does not modify the observable.
* Usefule for debugging.
* Tips & Tricks
* ngIf - ngIf="user$ | async as user; else guestUser"
* Resources
* https://rxjs-dev.firebaseapp.com/operator-decision-tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment