rxjs pattern(结合Angular)学习笔记

144 阅读2分钟

知识搬运工,原视频链接:www.youtube.com/watch?v=vtC…

之前看过一些rxjs的资料,理解起来很有难度,看了这个视频有很大的帮助。

本文将视频中的核心概念记录下来。建议先学习原视频,然后本文作为资料来复习查看

看完视频,你将学习到:

  • 什么是Observable
  • Observable做了什么
  • Subscription Observable Observer之间的关系以及示例
  • 什么是Pipe,怎么使用Pipe
  • 常用的四种rxjs pattern模式,结合一个Angular应用示例来看

RxJS Patterns 模式

image.png

  • Declarative Data Access Pattern
  • Retrieve on Action Pattern
  • Shape on Action Pattern
  • Retrieve Related Data Pattern

Terms术语

术语1 Observable

Observable is a colleaction of items over time.

image.png

Why Use an Observable?

image.png

What Does an Observable Do?

It does nothing until a consumer subscribes

When subsribed, the Observable begins emitting items or notifications to the consumer: next: The next item is emitted error: An error occurred and no more items are emitted complete: No more items are emitted

Angular Creates Observables

image.png

An Observable does nothing until a consumer subscribes

image.png

术语二 Subscription

image.png

Tip: Ensure each Observable is subscribed Ensure each subscription is unsubscribed

image.png

确保unsubsribe,以免内存泄漏 image.png

术语三 Observer

Oberver watches for emissions and notifications: next error complete

Observer is an object with three methods

通常不这样写:

image.png

箭头函数observer,放在subscribe里 image.png

Observable, Subscription, Observer

image.png

Pipe 管道

when you work with rxjs, you can specify a pipe which transforms each emitted item.

pipe it through a lowercase operator and it becomes a lowercase a, we can pipe that same a through an enlarged operator and we have a bigger lowercase a. That is how piping works, it takes in the emitted value, it performs some operation on it and then it emits to the next operator in the pipeline.

image.png

Common Piperable RxJS Operators

image.png

Using Pipe

start the stream with a subscribe, then we pipe through a set of operators

image.png

no need for an observer, because we can process the items instead through these pipable operators.

RxJS模式 Patterns

介绍4种RxJS模式 what you need to do to make your rxjs pipelines work, answering these three questions. image.png

Declarative Data Access Pattern

image.png

image.png Tip: use the async pipe

image.png

image.png

Retrive on Action Pattern

做一个下拉框查询,

image.png

听到action时,就要使用Subject或者BehaviorSubject了 image.png

image.png

image.png

image.png

image.png

image.png

Shape on Action Pattern

image.png

image.png

image.png

image.png

image.png

image.png

Retrive Related Data Pattern

image.png

image.png

image.png

image.png

总结

image.png