Home > Web Front-end > JS Tutorial > RxJS simplified with Reactables

RxJS simplified with Reactables

Barbara Streisand
Release: 2024-10-10 06:19:02
Original
1130 people have browsed it

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
Copy after login

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

*/

Copy after login

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

Copy after login

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;


Copy after login

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!

The above is the detailed content of RxJS simplified with Reactables. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template