2
我試圖看到(出於好奇)用純Rxjs重新實現基本的redux/redux-observable行爲有多複雜。只有RxJs才能觀察到重新實現?
這是我的承諾,但它似乎太簡單,不對。任何人都可以在我的邏輯中指出我的錯誤/缺陷嗎?
非常感謝您
// 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而不是從頭開始?」來自Ben Lesh的文章:[Ben Lesh文章](https://medium.com/@benlesh/redux-observable-ec0b00d2eb52) – TheoH
不客氣! – jayphelps