Javascript Redux 和 RxJS,有什么相似之处?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34497343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:26:32  来源:igfitidea点击:

Redux & RxJS, any similarities?

javascriptrxjsredux

提问by Oswaldo

I know Redux is a better "implementation" of Flux, or better saying it's a redesign to simplify things (application state management).

我知道 Redux 是 Fl​​ux 更好的“实现”,或者更好地说它是一种简化事物(应用程序状态管理)的重新设计。

I have heard a lot about reactive programming (RxJS), but I haven't dived to learn it yet.

我听说过很多关于反应式编程(RxJS)的知识,但我还没有深入学习。

So my question is: are there any intersection (anything in common) between this two technologies or they are complementary? ...or totally different?

所以我的问题是:这两种技术之间是否有任何交集(任何共同点)或者它们是互补的?……还是完全不同?

回答by André Staltz

In short, they are very different libraries for very different purposes, but yes there are some vague similarities.

简而言之,它们是用于非常不同目的的非常不同的库,但是确实存在一些模糊的相似之处。

Redux is a tool for managing state throughout the application. It is usually used as an architecture for UIs. Think of it as an alternative to (half of) Angular.

Redux 是一个用于管理整个应用程序状态的工具。它通常用作 UI 的架构。将其视为(一半)Angular 的替代品。

RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises.

RxJS 是一个反应式编程库。它通常用作在 JavaScript 中完成异步任务的工具。可以将其视为 Promise 的替代品。



Reactive programming is a paradigm (way of working and thinking) where data changes are observed from a distance. Data is not changed from a distance.

反应式编程是一种范式(工作和思维方式),可以从远处观察数据变化。数据不会从远处改变

Here is an example of changed from a distance:

这是一个从远处改变的例子:

// In the controller.js file
model.set('name', 'George');

The Model is changedfrom the Controller.

模型被改变从控制器。

Here is an example of observed from a distance:

这是一个从远处观察的例子:

// logger.js
store.subscribe(function (data) {
    console.log(data);
});

In the Logger, we observe the data changes that happen in Store (from a distance), and write to the console.

在 Logger 中,我们观察 Store 中发生的数据变化(从远处),并写入控制台。



Redux uses the Reactive paradigm just a little bit: the Store is reactive. You do not set its content from a distance. That's why there is no store.set()in Redux. The Store observes actions from a distance, and changes itself. And the Store allows others to observe its data from a distance.

Redux 稍微使用了 Reactive 范式:Store 是响应式的。您不会从远处设置其内容。这就是为什么store.set()Redux 中没有。商店从远处观察动作,并改变自己。Store 允许其他人从远处观察它的数据。

RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this "observing from a distance" pattern.

RxJS 也使用 Reactive 范式,但它不是一种架构,而是为您提供基本构建块Observables来完成这种“远距离观察”模式。

To conclude, very different things for different purposes, but share some ideas.

总而言之,出于不同目的,非常不同的事情,但分享一些想法。

回答by cmdv

They are very different things.

它们是非常不同的东西。

RxJS can be used to do Reactive Programming and is a very thorough library with 250+ operators.

RxJS 可用于进行响应式编程,是一个非常全面的库,拥有 250 多个运算符。

And Redux is as described on the github repo "Redux is a predictable state container for JavaScript apps".

Redux 如 github 存储库中所述“Redux 是 JavaScript 应用程序的可预测状态容器”。

Redux is just a tool to handle state in apps. But in comparison you could build a full app in just RxJS.

Redux 只是一个处理应用程序状态的工具。但相比之下,你可以只用 RxJS 构建一个完整的应用程序。

Hope this helps :)

希望这可以帮助 :)

回答by mdikici

Reduxis a just a state management library coming with well defined standards for update operations. As far as you stick with the standards you can keep your data flow sane and easy to reason. It also brings the ability to enhance the data flow with middlewares and store enhancers.

Redux只是一个状态管理库,带有明确定义的更新操作标准。只要您坚持标准,您就可以保持数据流的健全和易于推理。它还带来了通过中间件和存储增强器增强数据流的能力。

RxJSis a toolkit for reactive programming. You can actually think of every thing happening in your app as a stream. RxJS gives a very rich tool set to manage those streams.

RxJS是反应式编程的工具包。实际上,您可以将应用程序中发生的每一件事都视为流。RxJS 提供了一个非常丰富的工具集来管理这些流。

Where RxJS and Redux intercepts? In redux you update your state with actions and obviously these actions can be treated as streams. Using a middleware like redux-observable (you don't have to) you can implement your so called "business logic" in a reactive way. Another thing is that you can create an observable from your redux store which sometimes might be easier than using an enhancer.

RxJS 和 Redux 拦截在哪里?在 redux 中,你用动作更新你的状态,显然这些动作可以被视为流。使用像 redux-observable 这样的中间件(您不必这样做),您可以以反应方式实现所谓的“业务逻辑”。另一件事是您可以从您的 redux 存储创建一个可观察的对象,这有时可能比使用增强器更容易。

回答by Krishna Ganeriwal

To put it in short:

简而言之:

Redux:Flux inspired Library used for State Management.

Redux:用于状态管理的Flux 启发库。

RxJS:It is another Javascript library based on the reactive programming philosophy, used to deal with "Streams" (Observables, etc.) [Read about Reactive Programming to understand the Stream concepts].

RxJS:它是另一个基于反应式编程哲学的 Javascript 库,用于处理“流”(Observables 等)[阅读反应式编程以了解流概念]。

回答by Marcus R?dell

I just wanted to add some pragmatic differences from when I did Redux-inspired RxJS-code.

我只是想添加一些与我做受 Redux 启发的 RxJS 代码时的实际差异。

I mapped each action type to a Subject instance. Each stateful component will have a Subject that is then mapped into a reducer function. All reducer streams are combined with mergeand then scanoutputs the state. The default value is set with startWithjust before the scan. I used publishReplay(1)for states, but might remove it later on.

我将每个操作类型映射到一个 Subject 实例。每个有状态组件都有一个 Subject,然后映射到一个 reducer 函数中。所有的reducer流都与状态结合,merge然后scan输出。默认值设置startWithscan. 我用于publishReplay(1)状态,但稍后可能会删除它。

The react pure render function will be to only place where you produce event data by sending in all the producers/Subjects.

反应纯渲染功能将仅用于通过发送所有生产者/主题来产生事件数据的地方。

If you have child components, you need to describe how those states are combined into yours. combineLatestmight be a good starting point for that.

如果您有子组件,则需要描述这些状态如何组合到您的状态中。combineLatest可能是一个很好的起点。

Notable differences in implementation:

实现上的显着差异:

  • No middleware, just rxjs operators. I think this is the biggest power and weakness. You can still borrow concepts, but I find it hard to get help from sister communities like redux and cycle.js since it's yet another custom solution. That's why I need to write "I" instead of "we" in this text.

  • No switch/case or strings for action types. You have a more dynamic way of separating actions.

  • rxjs can be used as a tool elsewhere, and is not contained to state management.

  • Less number of producers than action types(?). I'm not sure about this, but you can have many reactions in parent components that listen to child components. That means less imperative code, and less complexity.

  • You own the solution. No framework needed. Good and bad. You will end up writing your own framework anyhow.

  • It's much more fractal, and you can easily subscribe to changes from a sub-tree, or multiple parts of the app state tree.

    • Guess how easy it is to do epics as redux-obseravble do? Really easy.
  • 没有中间件,只有 rxjs 操作符。我认为这是最大的力量和弱点。您仍然可以借用概念,但我发现很难从 redux 和 cycle.js 等姐妹社区获得帮助,因为它是另一种自定义解决方案。这就是为什么我需要在本文中写“我”而不是“我们”的原因。

  • 动作类型没有开关/大小写或字符串。你有一种更动态的分离动作的方式。

  • rxjs 可以用作其他地方的工具,并且不包含在状态管理中。

  • 生产者数量少于动作类型(?)。我不确定这一点,但是您可以在父组件中听到许多听子组件的反应。这意味着更少的命令式代码和更少的复杂性。

  • 您拥有解决方案。不需要框架。好和坏。无论如何,您最终都会编写自己的框架。

  • 它更加分形,您可以轻松订阅来自子树或应用程序状态树的多个部分的更改。

    • 猜猜像 redux-observable 那样做史诗有多容易?真的很容易。

I'm also working on much bigger benefits where the child components are described as streams. This means that we don't have to complect parent and child state in the reducers, since we can just ("just") recursively combine the states based on the component structure.

我也在致力于更大的好处,其中子组件被描述为流。这意味着我们不必在 reducer 中完成父状态和子状态,因为我们可以(“只是”)基于组件结构递归地组合状态。

I also think about skipping react and go with snabbdom or something else until React handles reactive states better. Why should we build our state upwards just to break it down via props again? So I will try to make a version 2 of this pattern with Snabbdom.

我还考虑跳过 React 并使用 snabbdom 或其他东西,直到 React 更好地处理响应状态。为什么我们要向上构建我们的 state 只是为了再次通过 props 分解它?因此,我将尝试使用 Snabbdom 制作此模式的第 2 版。

Here's a more advanced but small snippet where the state.ts file builds the state stream. This is the ajax-form component's state which gets an object of fields (inputs) with validation rules and css styles. In this file we just use the field names (object keys) to combine all the children's states into the form state.

这是一个更高级但很小的片段,其中 state.ts 文件构建状态流。这是 ajax-form 组件的状态,它获取具有验证规则和 css 样式的字段(输入)对象。在这个文件中,我们只使用字段名称(对象键)将所有子项的状态组合到表单状态中。

export default function create({
  Observable,
  ajaxInputs
}) {
  const fieldStreams = Object.keys(ajaxInputs)
  .map(function onMap(fieldName) {
    return ajaxInputs[fieldName].state.stream
    .map(function onMap(stateData) {
      return {stateData, fieldName}
    })
  })

  const stateStream = Observable.combineLatest(...fieldStreams)
  .map(function onMap(fieldStreamDataArray) {
    return fieldStreamDataArray.reduce(function onReduce(acc, fieldStreamData) {
    acc[fieldStreamData.fieldName] = fieldStreamData.stateData
    return acc
  }, {})
  })

  return {
    stream: stateStream
  }
}

While the code might not say much in isolation, it shows how you can build state upwards, and how you can produce dynamic events with ease. The price to pay is that you need to understand a different style of code. And I love to pay that price.

虽然代码可能不会单独说明太多,但它展示了如何向上构建状态,以及如何轻松生成动态事件。付出的代价是你需要理解不同风格的代码。我喜欢付出这个代价。