search
HomeWeb Front-endJS TutorialNative Observables, RxRxnd the observable that doesn&#t exist yet

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);

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>
  `;
}

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);

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>
  `;
}

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
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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment