DEV Community

Cover image for RxJS Simplified with Reactables
Dave Lai
Dave Lai

Posted on • Edited on

RxJS Simplified with Reactables

Introduction

RxJS is a powerful library but it has been known to have a steep learning curve.

The library's large API surface, coupled with a paradigm shift to reactive programming can be overwhelming for newcomers.

I created Reactables API to simplify RxJS usage and ease the developer's introduction to reactive programming.

Example

We will build a simple control that toggles a user's notification setting.

It will also send the updated toggle setting to a mock backend and then flash a success message for the user.

notification-toggle

Install RxJS & Reactables

npm i rxjs @reactables/core
Enter fullscreen mode Exit fullscreen mode

Starting with a basic toggle.

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

export type ToggleState = {
  notificationsOn: boolean;
};

export type ToggleActions = {
  toggle: () => void;
};

export const RxNotificationsToggle = (
  initialState = {
    notificationsOn: false,
  } as ToggleState
): Reactable<ToggleState, ToggleActions> =>
  RxBuilder({
    initialState,
    reducers: {
      toggle: (state) => ({
        notificationsOn: !state.notificationsOn,
      }),
    },
  });


const [state$, actions] = RxToggleNotifications();

state$.subscribe((state) => {
  console.log(state.notificationsOn);
});

actions.toggle();

/*
OUTPUT

false
true

*/

Enter fullscreen mode Exit fullscreen mode

RxBuilder creates a Reactable, which is a tuple with two items.

  1. An RxJS Observable the UI can subscribe to for state changes.

  2. An object of action methods the UI can call to invoke state changes.

No need for Subjects when using Reactables.

We can just describe the behaviour we want with pure reducer functions.

Reactables uses Subjects and various operators under the hood to manage state for the developer.

Adding API call and flashing success message

Reactables handle asynchronous operations with effects which are expressed as RxJS Operator Functions. They can be declared with the action/reducer that triggers the effect(s).

This allows us to leverage RxJS to the fullest in handling our asynchronous logic.

Lets modify our toggle example above to incorporate some asyncrounous behaviour. We will forgo error handling to keep it short.

import { RxBuilder, Reactable } from '@reactables/core';
import { of, concat } from 'rxjs';
import { debounceTime, switchMap, mergeMap, delay } from 'rxjs/operators';

export type ToggleState = {
  notificationsOn: boolean;
  showSuccessMessage: boolean;
};
export type ToggleActions = {
  toggle: (payload: boolean) => void;
};

export const RxNotificationsToggle = (
  initialState = {
    notificationsOn: false,
    showSuccessMessage: false,
  }
): Reactable<ToggleState, ToggleActions> =>
  RxBuilder({
    initialState,
    reducers: {
      toggle: {
        reducer: (_, action) => ({
          notificationsOn: action.payload as boolean,
          showSuccessMessage: false,
        }),
        effects: [
          (toggleActions$) =>
            toggleActions$.pipe(
              debounceTime(500),
              // switchMap to unsubscribe from previous API calls if a new toggle occurs
              switchMap(({ payload: notificationsOn }) =>
                of(notificationsOn)
                  .pipe(delay(500)) // Mock API call
                  .pipe(
                    mergeMap(() =>
                      concat(
                        // Flashing the success message for 2 seconds
                        of({ type: 'updateSuccess' }),
                        of({ type: 'hideSuccessMessage' }).pipe(delay(2000))
                      )
                    )
                  )
              )
            ),
        ],
      },
      updateSuccess: (state) => ({
        ...state,
        showSuccessMessage: true,
      }),
      hideSuccessMessage: (state) => ({
        ...state,
        showSuccessMessage: false,
      }),
    },
  });

Enter fullscreen mode Exit fullscreen mode

See full example on StackBlitz for:
React
| Angular

Lets bind our Reactable to the view. Below is an example of binding to a React component with a useReactable hook from @reactables/react package.

import { RxNotificationsToggle } from './RxNotificationsToggle';
import { useReactable } from '@reactables/react';

function App() {
  const [state, actions] = useReactable(RxNotificationsToggle);
  if (!state) return;

  const { notificationsOn, showSuccessMessage } = state;
  const { toggle } = actions;

  return (
    <div className="notification-settings">
      {showSuccessMessage && (
        <div className="success-message">
          Success! Notifications are {notificationsOn ? 'on' : 'off'}.
        </div>
      )}
      <p>Notifications Setting:</p>
      <button onClick={() => toggle(!notificationsOn)}>
        {notificationsOn ? 'On' : 'Off'}
      </button>
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

That's it!

Conclusion

Reactables helps to simplify RxJS by allowing us to build our functionality with pure reducer functions vs diving into the world of Subjects.

RxJS is then reserved for what it does best - composing our asynchronous logic.

Reactables can extend and do much more! Check out the documentation for more examples, including how they can be used to manage forms!

Auth0

Auth0 now, thank yourself later. 😌

Good things come in threes—like Custom Domain, Okta Connections, and Passwordless! And yes, they’re all in our upgraded free plan.

Try free today

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay