首頁 > web前端 > js教程 > 主體

使用 Reactables 簡化 RxJS

Barbara Streisand
發布: 2024-10-10 06:19:02
原創
1058 人瀏覽過

介紹

RxJS 是一個功能強大的函式庫,但眾所周知,它的學習曲線很陡峭。

這個函式庫龐大的 API 介面,再加上向反應式程式設計的典範轉移,可能會讓新手不知所措。

我創建了 Reactables API 來簡化 RxJS 的使用並簡化開發人員對反應式程式設計的介紹。

例子

我們將建立一個簡單的控制項來切換使用者的通知設定。

它也會將更新的切換設定傳送到模擬後端,然後向使用者顯示成功訊息。
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<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

*/

登入後複製

RxBuilder 建立一個 Reactable,它是一個包含兩個項目的元組。

  1. UI 可以訂閱狀態變更的 RxJS Observable。

  2. UI 可以呼叫以呼叫狀態變更的操作方法的物件。

使用 Reactable 時不需要主題

我們可以用純reducer函數來描述我們想要的行為。

Reactables 在幕後使用主題和各種運算符來管理開發人員狀態。

新增API呼叫並閃爍成功訊息

Reactables 處理非同步操作,其效果表示為 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<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,
      }),
    },
  });

登入後複製

在 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 (
    <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;


登入後複製

就是這樣!

結論

Reactables 讓我們可以使用純減速器函數建立功能,而不是深入主題世界,從而幫助簡化 RxJS。

然後,RxJS 被保留用於它最擅長的地方 - 組成我們的非同步邏輯。

Reactables 可以擴充並做更多事情!查看文件以了解更多範例,包括如何使用它們管理表單

以上是使用 Reactables 簡化 RxJS的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!