react编程式路由_React式编程中的可观察性简介

react编程式路由

One of the most challenging things for new developers to learn is the observer pattern. Understanding how to effectively use it with RxJS to deal with asynchronous data such as user events, HTTP requests or any other events that require waiting for something to complete is tricky.

最具挑战性的事情之一 供新开发者学习的是观察者模式。 了解如何与RxJS一起有效地使用它来处理异步数据,例如用户事件,HTTP请求或任何其他需要等待完成的事件,这很棘手。

What most people struggle with is the new approach. It requires a different mindset where visualization plays an important role. We think of data as a sequence of values that passes over time rather than as one single value that is retrieved once. This mindset is known as reactive programming.

大多数人都在挣扎的是新方法。 它需要一种不同的思维方式,其中可视化起着重要作用。 我们将数据视为随时间推移传递的一系列值,而不是一次获取一次的单个值。 这种思维方式被称为React式编程。

Since the Observer pattern is a fairly large ecosystem consisting of many important parts, I’ve chosen to narrow it down by focusing on Observables only. I’ll share other articles soon that cover the rest of the Observer pattern, such as how to deal with RxJS.

由于观察者模式是一个由许多重要部分组成的相当大的生态系统,因此我选择只关注可观察对象来缩小观察范围。 我将很快分享其他涉及Observer模式其余部分的文章,例如如何处理RxJS。

我们将讨论的主题: (Topics we’ll cover:)
  1. What does asynchronous really mean?

    异步到底是什么意思?
  2. Which pattern to use (Observer or Promise)

    使用哪种模式(观察者或承诺)
  3. How to create an Observable (code examples start here)

    如何创建一个Observable(代码示例从此处开始)
  4. How to subscribe to an Observable

    如何订阅可观察的
  5. How to unsubscribe to an Observable

    如何退订可观察对象

1.异步到底是什么意思? (1. What does asynchronous really mean?)

One of the things with the web, and the majority of languages, is that once you ask for data such as requesting a list of users from the server, you can’t guarantee that the data will be returned. There is an uncertainty issue.

网络和大多数语言的问题之一是,一旦您请求数据(例如从服务器请求用户列表),就无法保证会返回数据。 存在不确定性问题。

One of the reasons may be that the data is not present, the server may be broken, or the HTTP URL is not valid because someone has changed the query string.

原因之一可能是数据不存在,服务器可能损坏或HTTP URL无效,因为有人更改了查询字符串。

For that reason, along with a few others, we need to deal with such data asynchronously. We request the list of users, and wait until it is retrieved, but don’t stop the whole application for a simple operation.

因此,我们需要与其他一些数据异步处理。 我们请求用户列表,并等待直到检索到该列表,但不要为了简单的操作而停止整个应用程序。

It’s like telling a coworker to solve a task instead of sending the whole team; that would be an expensive and not a wise approach to take.

这就像告诉同事解决任务,而不是派遣整个团队。 那将是一种昂贵且不明智的方法。

Let’s clarify a misconception: the terms synchronous or asynchronous have nothing to do with multi-threading, where operations are executed at the same time. It simply means the operations are either dependent on or independent from each other, that’s it.

让我们澄清一个误解:同步或异步与多线程无关,在多线程中,操作是同时执行的。 这仅表示操作相互依赖或相互独立 ,就是这样。

Let’s compare the difference between synchronous and asynchronous to better understand how they really work.

让我们比较一下同步和异步之间的区别,以更好地了解它们的真正工作原理。

什么是同步? (What is Synchronous?)

With Synchronous events, you wait for one to finish before moving on to another task.

使用同步事件,您需要等待一个事件完成才能继续执行另一项任务。

Example: You are in a queue to get a movie ticket. You cannot get one until everybody in front of you gets one, and the same applies to the people queued behind you. Answered by themightysapien.

示例:您正在排队领取电影票。 在前面的每个人都得到一个之前,您无法获得一个,对排在您后面的人也是如此。 通过回答themightysapien

什么是异步? (What is Asynchronous?)

With asynchronous events, you don’t wait, you can move on to the next task until the data is available.

对于异步事件,您无需等待,可以继续进行下一个任务,直到数据可用为止。

Example: You are in a restaurant with many other people. You order your food. Other people can also order their food, they don’t have to wait for your food to be cooked and served to you before they can order. In the kitchen, restaurant workers are continuously cooking, serving, and taking orders. People will get their food served as soon as it is cooked. Answered by themightysapien.

示例:您与许多其他人一起在餐厅用餐。 您点菜。 其他人也可以点餐,他们不必等待您的食物煮熟并为您服务就可以点菜。 在厨房里,饭店工作人员不断地做饭,服务和点菜。 人们将在煮熟后立即食用食物。 通过回答themightysapien

Alright, so in short, this allows us to either wait for operations to happen before we can move on, or not wait until the data is ready.

好的,总之,这允许我们要么等待操作发生然后继续操作,要么不等数据准备好。

2.使用哪种模式(观察者或承诺) (2. Which pattern to use (Observer or Promise))

First of all, both the observer pattern and the promise pattern deal with asynchronous operations. Operations such as user events or HTTP requests, or any other events that execute independently.

首先,观察者模式和承诺模式都处理异步操作。 用户事件或HTTP请求之类的操作,或独立执行的任何其他事件。

The majority of operations today need some type of asynchronous/synchronous handling, and understanding how it works plays an important role when building robust apps.

如今,大多数操作都需要某种类型的异步/同步处理,并且在构建健壮的应用程序时,了解其工作原理至关重要。

It’s not meant to make your life harder, but easier. However, it thus requires a learning-curve which may be a painful approach, but the reward at the end is well worth it.

这并不是要让您的生活更艰难,而是更轻松。 但是,这需要学习曲线,这可能是一种痛苦的方法,但是最后的回报是值得的。

保持一种模式 (Stay with one pattern)

The difference lies in the complexity of the application. If you deal with a small app where the task is to simply get a list of users from the server, or to show active members, then promises with the Fetch API (read more) work fine.

不同之处在于应用程序的复杂性。 如果您处理的小型应用程序的任务是仅从服务器获取用户列表或显示活动成员,则使用Fetch API ( 了解更多信息 )的承诺可以很好地工作。

But if you deal with a large application with many asynchronous operations that require changing the data, performing multiple operations on a data stream, or reusing it in multiple places, then the observer pattern works great.

但是,如果您处理的大型应用程序具有许多异步操作,这些操作需要更改数据,对数据流执行多个操作或在多个位置重用它,那么观察者模式将非常有用。

我可以在一个项目中同时使用两种模式吗? (Can I use both patterns in one project?)

Yes, but it’s not recommended that you mix between two architectures which basically do the same thing (handle asynchronous events). Instead, stick with one, and learn more about it.

是的,但是不建议您在基本上做相同事情的两个体系结构之间混合使用(处理异步事件)。 相反,请坚持使用,并进一步了解它。

使用RxJS提高您的技能 (Boost your skills with RxJS)

With RxJS, you have access to 189 operators with documentation + other great resources. And each of these operators are simply callbacks that do something on the data stream.

使用RxJS,您可以使用文档+ 其他强大资源来访问189个运算符。 这些运算符中的每一个都只是在数据流上执行某些操作的回调。

If you are familiar with JavaScript’s functional prototypes (methods) such as map(), filter(), and reduce(), you’ll find them in RxJS. Note, the concept is the same but the written code is not.

如果您熟悉JavaScript的功能原型(方法),例如map()filter()reduce() ,则可以在RxJS中找到它们。 注意,概念是相同的,但是书面代码却不同。

So what is the difference between these two patterns?

那么这两种模式有什么区别?

Here’s a quick comparison between the observer pattern and the promise pattern. The key points are that a promise emits a single value(s) once the .then() callback is used, while an Observable emits multiple values as a sequence of data that passes over time. Another important point is that an Observable can be canceled or retried while a promise cannot. However, there are external packages that make it possible to cancel a promise.

这是观察者模式和承诺模式之间的快速比较。 关键是一旦使用.then()回调,promise就会发出一个值,而Observable会发出多个值,作为随时间推移的数据序列。 另一个重要的一点是,可观察对象可以被取消或重试,而承诺则不能。 但是,有一些外部程序包可以取消承诺。

3.我们如何创建一个可观察的? (3. How do we create an Observable?)

Here are a couple of ways one can create an Observable:

以下是创建Observable的几种方法:

  • create an Observable from scratch

    从头开始创建一个Observable
  • turn a promise into an Observable

    将诺言变为可观察
  • or use a framework that does it for you behind the scenes, such as Angular.

    或使用幕后为您做到的框架,例如Angular。
Did you know that Angular uses the Observer pattern extensively? All asynchronous operations such as HTTP GET or listening for events or value changes follow the observer pattern.
您知道Angular广泛使用Observer模式吗? 所有异步操作(例如HTTP GET或侦听事件或值更改)均遵循观察者模式。

If you ever want to mimic (test) a real-world scenario, so to say pass values over time, I highly recommend using the interval function. This passes values after x time in milliseconds. So if you have an interval where x is 2000ms — it passes each value (increments) after 2 seconds.

如果您想模拟(测试)真实场景,可以说随着时间的推移传递值,我强烈建议您使用间隔函数。 这将传递x时间(以毫秒为单位)之后的值。 因此,如果您有一个x为2000ms的间隔,则它会在2秒钟后传递每个值(增量)。

4.我们如何订阅一个可观察者? (4. How do we subscribe to an Observable?)

An Observable is simply a collection of data that waits to be invoked (subscribed) before it can emit any data. If you’ve worked with promises, then the way to access the data is to chain it with the then() operator or use the ES6 async/await.

一个Observable只是一组数据的集合,在它可以发出任何数据之前等待被调用(预订)。 如果您已使用诺言,那么访问数据的方法是将其与then()运算符链接或使用ES6 async/await

So to follow the previous example, how does one access the data?

因此,按照前面的示例,一个人如何访问数据?

As shown above, when we subscribe, we tell the Observable to pass us whatever it holds. It can be an array, a collection of events, or a sequence of objects and so forth.

如上所示,当我们订阅时,我们告诉Observable将其持有的内容传递给我们。 它可以是数组,事件的集合或对象序列等。

A common beginner-mistake I’ve seen among developers is that they do many operations on the Observable but get frustrated because they can’t see any results. You are not alone! I’ve made this mistake a couple of times and as a thumb-rule — always remember to subscribe.

我在开发人员中看到的一个常见的初学者错误是,他们在Observable上执行了许多操作,但由于看不到任何结果而感到沮丧。 你不是一个人! 我已经犯了几次这个错误,并且作为一个经验法则-始终记得订阅。

5.我们如何退订可观察对象? (5. How do we unsubscribe to an Observable?)

It is important to unsubscribe, otherwise we end up with a memory leak which slows down the browser. If you’ve worked with Angular, there is a pipe named asyncPipe which subscribes and unsubscribes automatically for you.

取消订阅很重要,否则最终会导致内存泄漏,从而降低浏览器的速度。 如果您使用过Angular,则有一个名为asyncPipe的管道可以为您自动订阅和取消订阅。

The way we unsubscribe is that we create a reference to each Observable that is subscribed by creating a variable to preserve its current state. And then, for each variable, we chain it with the unsubscribe() method. Remember that you can only unsubscribe after you’ve subscribed. It’s fairly simple but often forgotten.

取消订阅的方式是,我们通过创建变量以保留其当前状态来创建对所订阅的每个Observable的引用。 然后,对于每个变量,我们使用unsubscribe()方法将其链接。 请记住,只有订阅后才能取消订阅。 这很简单,但经常被遗忘。

Notice, if you unsubscribe here, Observable_1 and Observable_2 will output the data before it is unsubscribe because these are cold Observables (not time-dependent), while Observable_3 and Observable_4 will not output anything because these are hot Observables (time-dependent).

请注意,如果您在此处取消订阅,则Observable_1Observable_2将在取消订阅之前输出数据,因为它们是冷的Observable(与时间无关),而Observable_3Observable_4则不会输出任何数据,因为它们是热的Observable(与时间有关)。

摘要 (Summary)

As mentioned above, the most challenging part of learning the observer pattern is the mindset. A mindset where we look at values differently, such as a sequence of data that emits over time. In this article, we’ve covered types of ways we can create an Observable, as well as how to subscribe and unsubscribe.

如上所述,学习观察者模式中最具挑战性的部分是心态。 我们以不同的方式看待值的心态,例如随着时间推移而发出的数据序列。 在本文中,我们介绍了创建Observable的方式类型以及如何订阅和取消订阅。

I recommend using the observer pattern because it provides everything that the promise pattern offers, and much more. It also provides a few great operators to prevent users from sending thousands of unnecessary requests to the backend.

我建议使用观察者模式,因为它提供了promise模式所提供的一切,还有更多。 它还提供了一些出色的运算符,以防止用户向后端发送数千个不必要的请求。

One of them is debonceTime which gives the user enough time to write a complete word, and then send one request instead of a request for every character. You can, of course, achieve this with a simple promise, but that requires some lines of code.

其中之一是debonceTime ,它为用户提供了足够的时间来写一个完整的单词,然后发送一个请求,而不是每个字符的请求。 当然,您可以通过简单的承诺来实现这一目标,但这需要一些代码行。

I’ll cover more about reactive programming in the near future, stay tuned!

我将在不久的将来介绍有关React式编程的更多信息,敬请期待!

If you are interested to learn more about the web-ecosystem, here are few articles I’ve written to boost your web skills, enjoy :)

如果您有兴趣了解有关网络生态系统的更多信息,请阅读以下几篇文章,以提高您的网络技能,请享受:)

If you want to become a better web developer, start your own business, teach others, or improve your development skills, you can find me on Medium where I publish on a weekly basis. Or you can follow me on Twitter, where I post relevant web development tips and tricks.

如果您想成为一个更好的Web开发人员,开始自己的业务,教别人或提高开发技能,可以在我每周出版的Medium上找到我。 或者,您可以在Twitter上关注我,我在其中发布了相关的Web开发技巧和窍门。

P.S. If you enjoyed this article and want more like these, please clap ❤ and share with friends that may need it, it’s good karma.

PS:如果您喜欢这篇文章并且想要更多类似的文章,请拍手❤并与可能需要它的朋友分享,这是很好的业障。

翻译自: https://www.freecodecamp.org/news/an-introduction-to-observables-in-reactive-programming-1cfd3e23bb94/

react编程式路由

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值