繁体   English   中英

仅使用RxJs重新实现redux可观察到的?

[英]Reimplement redux observable with only RxJs?

我试图(出于好奇)看到用纯Rxj重新实现基本的redux / redux-observable行为是多么复杂。

这是我对它的看法,但看起来非常简单。 任何人都可以指出我的逻辑中的任何错误/缺陷吗?

非常感谢你

 // set up the store.dispatch functionnaly through a subject (action$.next() is like store.dispatch()) var action$ = new Rx.Subject() // Create epics that do nothing interesting function epic1(action$) { return action$.filter(action => action.type == "test").delay(1000).mapTo({ type: "PONG" }) } function epic2(action$) { return action$.filter(action => action.type == "test2").delay(2000).mapTo({ type: "PING" }) } //.... //Later on, Merge all epic into one observable // function activateAndMergeEpics(action$, ...epics) { // give the action$ stream to each epic var activatedArray = epics.map(epic => epic(action$)) // merge them all into one megaObservable var merged = Rx.Observable.merge(...activatedArray) return merged } var merged = activateAndMergeEpics(action$, epic1, epic2) // Pipe your megaObservable back inside the loop so // you can process the action in your reducers var subscription = merged.subscribe(action$) function rootReducer(state = {}, action) { console.log(action) return (state) } // Generate your state from your actions var state$ = action$.scan(rootReducer, {}) // Do whatever your want now, like... // state$.map(route).map(renderdom) // Let's juste subscribe to nothing to get the stream pumping state$.subscribe() // Simulate a dispatch action$.next({ type: "test" }) // Another one action$.next({type:"test2"}) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.3/Rx.min.js"></script> 

是的,你已经完全掌握了核心功能。

我希望你不介意一些不请自来的建议:如果你这样做只是为了了解它是如何工作的,我为你鼓掌! 即使在程序员中也是如此,这是一个如此伟大且令人惊讶的罕见特征。 我确实想提醒你不要使用你自己的家庭滚动redux克隆,因为你失去了很多redux的巨大好处; devtools,中间件,增强器。 您丢失了所有内置的断言/错误检查,这实际上是redux中的大部分代码(其中一些代码在生产版本中被删除)。 您还会对多年来出现的边缘情况进行修复,有时为什么给定的库可能会在没有该上下文的情况下显得不必要地复杂化。

你可以添加所有这些东西,但那时它只是redux🙃

如果您决定沿着这条路走下去,请查看一些现有的基于RxJS的克隆,以获取您的灵感(或协作):

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM