仅使用 RxJs 重新实现 redux observable?

Reimplement redux observable with only RxJs?

我想看看(出于好奇)用纯 Rxjs 重新实现基本的 redux / redux-observable 行为会有多复杂。

这是我的看法,但它似乎太简单了,不可能是正确的。谁能指出我逻辑中的任何 errors/flaws?

非常感谢

// 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 的很多巨大好处;开发工具、中间件、增强器。你失去了它所有内置的 assertions/error 检查,这实际上是 redux 中的大部分代码(其中一些在生产构建中被剥离)。您还会对多年来出现的边缘情况进行松散修复,这有时就是为什么给定的库对于没有该上下文的任何人来说可能显得不必要的复杂。

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

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