Logo

dev-resources.site

for different kinds of informations.

Reusable, Extensible and Testable State Logic with Reactive Programming.

Published at
11/29/2024
Categories
svelte
rxjs
javascript
frontend
Author
laidav
Categories
4 categories in total
svelte
open
rxjs
open
javascript
open
frontend
open
Author
6 person written this
laidav
open
Reusable, Extensible and Testable State Logic with Reactive Programming.

State in UI Components

When we start introducing state into a UI component it is often tempting to do something like this:

Simple Counter Example in Svelte:

<script>
  let count = $state(0);
</script>

<button onclick={() => count++}>
  clicks: {count}
</button>
Enter fullscreen mode Exit fullscreen mode

Problem

We use Svelte here but same the issue can apply in any UI framework.

Off the bat we have tightly coupled our state logic with the component - the increment functionality is coded right in the template.

With this set up we can not reuse the counter logic in:

  • other UI components
  • other business logic that requires a counter
  • other UI frameworks

We also cannot test the counter logic without rendering the component. If the component has other functionality coupled with it, isolating the counter logic would not be possible.

Solution

Separate state logic from the UI component so it can be implemented and tested independently. This will make the logic more reusable and UI components only need to listen for state changes and render. Consider the following:

<script>
  import { RxCounter } from './RxCounter';

  const [count, { increment }] = RxCounter();
</script>

<button onclick={increment}>
  Count: {$count}
</button>
Enter fullscreen mode Exit fullscreen mode

See full example on StackBlitz

If you compare above with our original example, all the logic for the counter is now encapsulated in RxCounter (we will show the implementation later).

count is an RxJS Observable that emits the new count state. increment is an action method the UI can call to invoke state changes.

Svelte has a nice built in way of subscribing to observables in the template as seen with the $count template variable. Subscribing to an observable in any UI framework is not terribly difficult, and many frameworks have APIs to help accomplish this.

Implementing RxCounter

Information and Disclaimer: We will make use of Reactables API created by the author. It is a state management solution that leverages RxJS to make reactive programming easier.

Get the Reactables Core Package and create RxCounter.

npm i @reactables/core

import { RxBuilder } from '@reactables/core';

export const RxCounter = () =>
  RxBuilder({
    initialState: 0,
    reducers: {
      increment: (count) => count + 1,
    },
  });

Enter fullscreen mode Exit fullscreen mode

RxBuilder returns a Reactable.

A Reactable is a tuple with its first item being an RxJS Observable emitting state changes and second item being a dictionary of action methods for triggering state updates.

The state is reactive, meaning the state responds to changes via its reducer functions. When an increment action triggered by the UI is received, the reactable reacts and its observable emits the new state.

Note RxCounter is now completely decoupled from the view layer and can be used in any UI framework!

Testing the Counter

To test a Reactable, we subscribe to its state observable and invoke its action methods to test its behaviour. We can assert the observable's emitted values matches the desired behaviour.

This can be done with RxJS’s built in Marble Testing.

import { RxCounter } from './RxCounter';
import { Subscription } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';

describe('RxCounter', () => {
  let testScheduler: TestScheduler;
  let subscription: Subscription;

  beforeEach(() => {
    testScheduler = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });
  });
  afterEach(() => {
    subscription?.unsubscribe();
  });

  it('should increment', () => {
    testScheduler.run(({ expectObservable, cold }) => {
      // Create Counter Reactable
      const [count$, { increment }] = RxCounter();

      // Call actions
      subscription = cold('--b', {
        b: increment,
      }).subscribe((action) => action());

      // Assertions
      expectObservable(count$).toBe('a-b', {
        a: 0,
        b: 1,
      });
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

Extending the Counter

With the state logic isolated from the view, we can also extend the functionality of RxCounter and create a RxDoubleCounter that has the ability to double the count.

import { RxBuilder } from '@reactables/core';

export const RxCounter = (options) =>
  RxBuilder({
    initialState: 0,
    reducers: {
      increment: (count) => count + 1,
      ...options?.reducers,
    },
  });

export const RxDoubleCounter = () =>
  RxCounter({
    reducers: { doubleCount: (count) => count * 2 },
  });

Enter fullscreen mode Exit fullscreen mode

See full example on StackBlitz

Conclusion

Implementing state logic directly in UI components makes the logic harder to reuse and test.

We can program the state logic reactively with Reactables and test it in isolation. This produces a unit of reactive state logic that is highly reusable in both the view and logic layer.

We did a simple counter example here, but Reactables are extensible and composable for much more complex state management scenarios (i.e data fetching, forms etc...). Check out the docs to learn more!

rxjs Article's
30 articles in total
Favicon
rxjs
Favicon
Angular Signals and Their Benefits
Favicon
Migrando subscribe Callbacks para subscribe arguments no RxJS
Favicon
New in Angular: Bridging RxJS and Signals with toSignal!
Favicon
RxSignals: The Most Powerful Synergy in the History of Angular 🚀
Favicon
Virtually Infinite Scrolling with Angular
Favicon
Building a Collapsible UI Component in Angular: From Concept to Implementation 🚀
Favicon
Disabling button on api calls in Angular
Favicon
Angular Dependency Injection — Inject service inside custom Rxjs operators
Favicon
Unsubscribe Observable! why is it so important?
Favicon
Harnessing the Power of RxJS with React for Asynchronous Operations
Favicon
DOM Observables, Rx7, Rx8 and the observable that doesn't exist yet
Favicon
Advanced RxJs Operators You Know But Not Well Enough pt 2.
Favicon
Observables in Node.js: Transforming Asynchronous Chaos into Elegant Code
Favicon
Reusable, Extensible and Testable State Logic with Reactive Programming.
Favicon
Understanding RxJS and Observables in Angular: A Beginner-Friendly Guide
Favicon
Are Angular Resolvers on Life Support ?
Favicon
Creating Custom rxResource API With Observables
Favicon
Forestry: The Best State System for React and (not React)
Favicon
📢 Announcing the New Reactive State Management Libraries! 🎉
Favicon
Reactables: Reactive State Management for any UI Framework.
Favicon
Hot vs Cold Observables in Angular: Understanding the Difference
Favicon
RxJS Simplified with Reactables
Favicon
How I structure my Angular components with Signals
Favicon
Angular LAB: let's create a Visibility Directive
Favicon
Difference between mergeMap vs switchMap vs concatMap vs exhaustMap
Favicon
How Signals Improve Your App Performance
Favicon
The Article I Took So Long to Write: Concepts about Reactive Programming and RxJS
Favicon
Tame Your Asynchronous World with RxJS
Favicon
Custom RxJS Operators to Improve your Angular Apps

Featured ones: