【问题标题】:Reimplement redux observable with only RxJs?仅使用 RxJs 重新实现可观察的 redux?
【发布时间】:2018-03-16 20:45:13
【问题描述】:

我想看看(出于好奇)用纯 Rxjs 重新实现基本的 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>

【问题讨论】:

    标签: javascript redux rxjs redux-observable


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 哇,创作者自己的回答,酷!好吧,感谢您的建议和回答!我已经读过“为什么你使用 Redux 而不是从头开始?”来自 Ben Lesh 的文章:Ben Lesh article
    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 2018-08-29
    • 2019-12-10
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    相关资源
    最近更新 更多