「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > Reactables で簡素化された RxJS

Reactables で簡素化された RxJS

2024 年 11 月 5 日に公開
ブラウズ:256

導入

RxJS は強力なライブラリですが、学習曲線が急であることが知られています。

ライブラリの大規模な API サーフェスは、リアクティブ プログラミングへのパラダイム シフトと相まって、初心者にとっては圧倒される可能性があります。

RxJS の使用法を簡素化し、開発者がリアクティブ プログラミングを簡単に導入できるように、Reactables API を作成しました。

ユーザーの通知設定を切り替える簡単なコントロールを構築します。

また、更新されたトグル設定をモック バックエンドに送信し、ユーザーに成功メッセージをフラッシュします。
RxJS simplified with Reactables

RxJS と Reactables をインストールする

npm i rxjs @reactables/core

基本的なトグルから始めます。

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 は、2 つの項目を含むタプルである Reactable を作成します。

  1. UI が状態変更をサブスクライブできる RxJS Observable。

  2. 状態変更を呼び出すために UI が呼び出すことができるアクション メソッドのオブジェクト。

Reactables を使用する場合はサブジェクトは必要ありません.

純粋なリデューサー関数を使用して、必要な動作を記述するだけです。

Reactables は、サブジェクトとさまざまな演算子を内部で使用して、開発者の状態を管理します。

API呼び出しの追加と成功メッセージの点滅

Reactable は、RxJS オペレーター関数として表現されるエフェクトを使用して非同期操作を処理します。これらは、エフェクトをトリガーするアクション/リデューサーで宣言できます。

これにより、非同期ロジックを処理する際に RxJS を最大限に活用できるようになります。

上記のトグルの例を変更して、非同期動作を組み込んでみましょう。短くするためにエラー処理は省略します。

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

StackBlitz の完全な例を参照してください:
反応する |角度

Reactable をビューにバインドしましょう。以下は、@reactables/react パッケージの useReactable フックを使用して React コンポーネントにバインドする例です。

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;

それでおしまい!

結論

Reactables は、Subject の世界に飛び込むのではなく、純粋なリデューサー関数を使用して機能を構築できるようにすることで、RxJS を簡素化するのに役立ちます。

RxJS は、非同期ロジックの構成という最適な作業のために予約されます。

Reactable は拡張してさらに多くのことを行うことができます。 フォームの管理に使用する方法など、その他の例については、ドキュメントをご覧ください。

リリースステートメント この記事は次の場所に転載されています: https://dev.to/laidav/rxjs-simplified-with-reactables-3abi?1 侵害がある場合は、[email protected] に連絡して削除してください。
最新のチュートリアル もっと>

免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。

Copyright© 2022 湘ICP备2022001581号-3