Skip to content

How to use RxJS with Svelte

The Svelte's and RxJS uncovered synergy

JavaScript, Svelte, Reactive Programming1 min read

All the code exposed in this article can be seen in this live demo.

Svelte is an increasingly famous JavaScript framework; the community appears to be reacting positively to the developer experience offered by Svelte. RxJS has increasingly become a standard for Reactive Programming mainly due to Angular’s endorsement that builds its core functionalities around Observables, and the framework naturally interfaces with RxJS.

Svelte has a reactive nature that makes it extremely suitable to integrate with RxJS. Why would anybody put the effort? Well, simply put, you can leverage the whole RxJS ecosystem and APIs to manipulate data streams that would perfectly plug into Svelte. Let’s look at a small example where we regularly pull data from a set of characters in a public Game of Thrones API.

1const CHARACTERS_IDS = [583, 582, 581];
2let gotCharacters = of([]);
3const ajaxCharacters = () =>
4 =>
5 ajax({
6 method: 'get',
7 url: `${cid}`,
8 })
9 );
10gotCharacters = interval(5000).pipe(
11 tap(() => console.log('fetching characters...')),
12 switchMap(() => combineLatest(...ajaxCharacters(CHARACTERS_IDS))),
13 startWith([])
16 {#each $gotCharacters as c}
17 <li id="{`character-${}`}">
18 <ul>
19 <li id="{`character-${}-name`}">
20 Name: {}, Played by: {c.playedBy}
21 </li>
22 </ul>
23 </li>
24 {/each}

See how $gotCharacters within the Svelte template language auto subscribed to what originally is an RxJS stream? We’re directly streaming data to the UI with no boilerplate in between whatsoever to pull values out of the stream of us! In this small example, we see how we can have an RxJS flavored implementation within a Svelte component, leveraging the full power of RxJS operators to create and manipulate data streams.

We can say Svelte is the “new cool kid in the block”. It has enlarged its community over the years. Svelte 3 comes with reactivity at its core, making it suitable to plugin RxJS into Svelte applications.

“As usual, React and Vue lead the pack, but Svelte is quickly establishing itself as a very serious contender for the front-end crown.“, State of JS 2020: Front-end Frameworks

RxJS is known to be the go to library when it comes to programming with streams. Reactive programming is famous for making complex things easier by offering an extensive API of operators that give developers extreme power and flexibility when writing complex event-driven user interfaces.

All the code exposed in this article can be seen in this live demo.

If you liked this article, consider sharing (tweeting) it to your followers.