"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > RxJS simplified with Reactables

RxJS simplified with Reactables

Published on 2024-11-05
Browse:913

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.
RxJS simplified with Reactables

Install RxJS & Reactables

npm i rxjs @reactables/core

Starting with a basic toggle.

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

export type ToggleState = {
  notificationsOn: boolean;
};

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

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


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

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

actions.toggle();

/*
OUTPUT

false
true

*/

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 =>
  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,
      }),
    },
  });

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 (
    
{showSuccessMessage && (
Success! Notifications are {notificationsOn ? 'on' : 'off'}.
)}

Notifications Setting:

); } export default App;

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!

Release Statement This article is reproduced at: https://dev.to/laidav/rxjs-simplified-with-reactables-3abi?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3