”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Reactables 简化 RxJS

使用 Reactables 简化 RxJS

发布于2024-11-05
浏览:756

介绍

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 =>
  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 可以调用以调用状态更改的操作方法的对象。

使用 Reactables 时不需要主题.

我们可以用纯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 =>
  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 允许我们使用纯减速函数构建功能,而不是深入主题世界,从而帮助简化 RxJS。

然后,RxJS 被保留用于它最擅长的事情 - 组成我们的异步逻辑。

Reactables 可以扩展并做更多事情!查看文档以获取更多示例,包括如何使用它们管理表单

版本声明 本文转载于:https://dev.to/laidav/rxjs-simplified-with-reactables-3abi?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3