Home Web Front-end JS Tutorial Native Observables, RxRxnd the observable that doesn&#t exist yet

Native Observables, RxRxnd the observable that doesn&#t exist yet

Dec 29, 2024 am 05:37 AM

Native Observables, RxRxnd the observable that doesn

A lot of interesting things are happening right now.

RxJS 7 rocks, RxJS 8 is in alpha, it appears to be usable and so are the new Native Observables which are available in Chrome Today!

Can we use them together?
Short answer, kind of no. Technically they're all Observables, so should speak the same language, right? It's just .subscribe, .next, .error, .complete, and voilà...

Well, almost. Except RxJS makes some additional effort to ensure it's dealing with true Obsevables and not the "cheap imports" ?.
So it diligently checks for Symbol.observable or @@observable to be present, so you could technically monkey-patch those into the DOM Observable by doing Observable.prototype['@@observable'] = function(){ return this }, but... even if you succeed and you manage to plug both together via document.when('click').subscribe(new Subject()), it will fail again because RxJS streams make references to their own this, internally, which now will point elsewhere... so it breaks.

Hard luck, we need a custom bridge that subscribes to the Native Observable and forwards data to RxJS land.

Great, suppose we did that, sure, it would work. You would suddenly be able to do something like the following, provided you have this wrap silly function, done:

const clickCount = rx(
  wrap(document.when('click')),
  scan(x=>x+1, 0),
);

clickCount.subscribe(doSomething);
Copy after login
Copy after login

Anyway, whilst the above could already qualify as some kind of news, it's not the really interesting part, at all, yet!

The interesting part

The interesting part here comes when we talk about using Observables in the real world, in real applications, which is typically inside web frameworks or smaller UI libraries.

Consider the case of a click-counter button, using Observables, inside a JavaScript "Component".

import { Subject, scan } from 'rxjs';
import { rml } from 'rimmel';

const Component = () => {
  const counter = new BehaviorSubject(0).pipe(
    scan(x=>x+1)
  );

  return rml`
    <button onclick="${counter}">hit me</button>
    Count: <span>${counter}</span>
  `;
}
Copy after login
Copy after login

Now, with Native DOM Observables we have a couple of interesting problems. Subject doesn't exist, BehaviorSubject doesn't either.
In addition to that, it doesn't even have a .pipe() method to pass operators in.
Lastly, its native operators are all methods of the Observable class, not functions.

So, the big question is: how do you call the methods of an object that... doesn't exist yet?

(You're probably lost at this point... I know, hold up)

The new way to create Observables looks like element.when(eventName). It's a native call to the DOM.
However, we're now in a template, we're in a JavaScript Component. None of the HTML has been added to the DOM yet, so no call to .when() could have been possibly made.

And we want to call .map().inspect().filter() on it!

An oversight? RxJS used to sport the same interface until a few years ago (others like Bacon and Zen Observables still do), but to help tree-shaking, they've split all operator methods into operator functions, so now you can import just what you need, making your apps lighter. Great!

The Observature

So, back to our new situation, how do we solve that from within a component?
Sure, well, that's easy! We either get Subject and BehaviorSubject in the WICG proposal (spoiler: for now we don't), or... we get creative, hack the system and conceive something like a proxy that helps us pretend that the Native DOM Observable is there, even if it's not, so we can call its native operator methods. ?

I called it... the Observature.

Observable Future = Observature. Observaturus is Latin for "one who will observe", so if we force that into English, it should sound something like that.

Good, so what would it all look like in code?

const clickCount = rx(
  wrap(document.when('click')),
  scan(x=>x+1, 0),
);

clickCount.subscribe(doSomething);
Copy after login
Copy after login

Yay, look at that! We have something here: new Observature(0).scan(x=>x 1).
Let me explain this.
It's technically like creating a new BehaviorSubject(0).scan(x=>x 1) except for one thing: there's no BehaviorSubject anymore. ?
The Observature is just a proxy. It exposes methods from Observable and Observer for later subscription and later binding!
If you call .scan(fn), it will just remember to call .scan on the actual Observable it will be subscribed to, when the time comes.

So, what interesting stuff do Observatures bring?
First is the fact they're not actual Subjects, so when you run the code above, the operator function you provide will run at level 1/2 in the stack. It could be lighter and faster than anything you've seen before, from click to sink. No, haven't run benchmarks yet and I'm not bothered, it's the concept that matters, for now.

Ah, another little note. There's no Observable.scan(), too, in the spec now, so one thing we can do is to monkey-patch at the moment, but again, those are just tiny implementation details. We have native Observables, that's the big deal!

To stay 100% native, for other use cases you can just use .map() and .filter(), but in my experience you can't live a proper life without scan(), as well.

RxJS 8

Ok, so... the above was using native stuff, no RxJS.
How would it all look like with RxJS8?
My answer is I've got no idea, ask @benlesh, he's your man :)

The current obstacles are the same: native Observables aren't recognised by RxJS, so there's a little bit of work to do. It could all look something like this:

import { Subject, scan } from 'rxjs';
import { rml } from 'rimmel';

const Component = () => {
  const counter = new BehaviorSubject(0).pipe(
    scan(x=>x+1)
  );

  return rml`
    <button onclick="${counter}">hit me</button>
    Count: <span>${counter}</span>
  `;
}
Copy after login
Copy after login

What's your thoughts? Would you use something like this?

For now, you can play with DOM Observables, Observatures on this Stackblitz

Drop a message to leave your thoughts.

The above is the detailed content of Native Observables, RxRxnd the observable that doesn&#t exist yet. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Apr 04, 2025 pm 02:09 PM

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...

See all articles