2017-10-05 24 views
2

순수 Rxj로 기본 redux/redux-observable 동작을 다시 구현하는 것이 얼마나 복잡한지를 (호기심에서) 보려고합니다.RxJs에서만 관측 가능한 reduxplement?

여기 내 걸리 겠지만 옳기는 매우 간단합니다. 아무도 내 논리에서 오류/결함으로 나를 가리킬 수 있습니까?

당신에게 대단히 감사합니다

// 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>

답변

1

그래, 당신은 완전히 핵심 기능을 가지고있다.

자발적인 조언이 필요하지 않으시길 바랍니다. 어떻게 작동 하는지를 배우기 만한다면, 나는 당신에게 박수를 보냅니다! 이것은 프로그래머들 사이 에서조차도 매우 놀랍고 희귀 한 특성입니다. 나는 당신이 redux의 거대한 이득을 많이 잃어 버리기 때문에 자신의 집 압연 redux 클론을 사용하는 것에 대해주의를 기울이고 싶다; devtools, 미들웨어, 인핸서. 당신은 모든 built-in assertions/error checking을 잃어 버린다. 실제로는 redux의 대부분의 코드이다 (일부는 프로덕션 빌드에서 제거된다). 또한 수년에 걸쳐 쉐이크 된 엣지 케이스에 대한 수정 사항이 누락되었습니다. 이는 종종 주어진 라이브러리가 해당 컨텍스트없이 누구에게나 불필요하게 복잡해 보일 수있는 이유 일 수 있습니다.

당신은 모든 일을 추가 할 수 있지만, 그 길을 갈 기존의 몇 가지 체크 아웃하기로 결정한다면 그것은 단지 REDUX

이 될 것입니다 당신의 영감 (또는 협력)에 대한 클론을 RxJS을 기반 :

+0

와우, 제작자의 답변은 멋집니다. 귀하의 조언과 당신의 대답에 대해 고마워요! 나는 이미 "왜 Redux로하고 처음부터하지 않았습니까?"라고 읽었습니다. Ben Lesh 기사 : [Ben Lesh article] (https://medium.com/@benlesh/redux-observable-ec0b00d2eb52) – TheoH

+0

여러분을 환영합니다! – jayphelps

관련 문제