未加星标

Homemade observables

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

On this episode we will build our own implementation of an observable. I hope that by the end of this post we gain a better understanding of this pattern that is used in libraries like RxJS.

About Observables What is it?

Lets start with my definition of observable.

An Observable is a function that follows a convention and is used to connect a data source with a consumer.

In our case a data source is something that produces values. And, a consumer is something that receives values from a data source.

Fun facts Observables are lazy

That means that they would not do any kind of work until it's absolutly necessary. Nothing will happen until you subscribe to them.

They can emit multiple values

Depending on the data source you can receive a finite number of values or an infinite stream of values.

They can be synchronous or asynchronous

It all depends on their internal implementation. You can setup an observable that process some stream of data in a synchronous way or create one from an event that can happen over time.

Some rules

Remember when I said that observables follow a convention? Well, we are going to make our own arbitrary rules that our implementation will follow. This are important because we are going to build a little ecosystem around our observables.

Here we go:

An observable instance will have a subscribe method. The observable "factory" will take a subscriber function as a parameter. The subscriber function will take an observer object as a parameter. The observer object can implement these methods next, error and complete.

Now, lets do stuff.

The code Factory function

function Observable(subscriber) { return { subscribe: observer => subscriber(observer) }; } // I swear to you, this works.

That is less magical than I thought. What we see here is that the Observable factory is just a way to postpone the work that has to be done until you call subscribe. The subscriber function is doing the heavy lifting, that's good because we can do whatever we want in there, is what will make our observables useful.

So far I haven't done a really good job explaining the observer and the subscriber roles. I hope it'll become clear when you see them in action.

A use case

Say that we want to convert an array into an Observable. How can we do this?

Lets think about what we know:

We can do all of our logic inside the subscriber function. We can expect an observer object with three methods, next, error and complete

We can use the methods of the observer object as communication channels. The next function will receive the values that our data source gives us. The error will handle any errors we throw at it, it will be like the catch function in the Promise class. And, we will use the complete method when the data source is done producing values.

Our array to observable function could look like this.

function fromArray(arr) { return Observable(function(observer) { try { arr.forEach(value => observer.next(value)); observer.complete(); } catch (e) { observer.error(e); } }); } // This is how we use it var arrayStream = fromArray([1, 2, 3, 4]); arrayStream.subscribe({ next: value => console.log(value), error: err => console.error(err), complete: () => console.info('Nothing more to give') }); // And now watch all the action on the console Be safe

Right now the observer object is basically a lawless town, we could do all sorts of weird stuff like sending yet another value to next even after we call the complete method. Ideally our observables should give us some guarantees, like:

The methods on the observer object should be optional. The complete and error methods need to call the unsubscribe function (if there is one). If you unsubscribe, you can't call next, complete or error. If the complete or error method were called, no more values are emitted. Interactive example

We can actually start doing some interesting things with what we learned so far. In this example I made a helper function that let me create an observable from a DOM event.

Conclusion

This is definitely not the end. There will be a second part to this.

Observables are a powerful thing, with a little bit of creativity you can turn anything you want into an observable. Really. A promise, an AJAX request, a DOM event, an array, a time interval... another observable (think about that for a second)... anything you can imagine can be a source of data that can be wrapped in an observable.

Other sources Learning Observable By Building Observable Observables, just powerful functions?

Thank you for reading.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

tags: observer,will,function,observable,The,our
分页:12
转载请注明
本文标题:Homemade observables
本站链接:https://www.codesec.net/view/586936.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(25)