reactjsreduxrxjsnext.jsredux-observable

How to share a variable between epics that are in different files?


I'm using redux-observable in my nextjs web application. There is a variable which has to be set in epic1 and accessed later in epic2:

let sharedVariable;

const epic1 = (action$, state$) => {
    return action$.pipe(
        // check if the dispatched action is of type action1
        filter(action1.match),
        tap((action) => {
            // create a new instance of A and assign
            // it to sharedVariable
            if (!sharedVariable) {
                sharedVariable = new A();
            }
        }),
        mergeMap((action) => {
            ...
        }),
    )
}

const epic2 = (action$, state$) => {
    return action$.pipe(
        // check if the dispatched action is of type action2
        filter(action2.match),
        map((action) => {
            if (sharedVariable) {
                return action3();
            } else {
                return action4();
            }
        }),
    )
}

I want to put the epics on different files: epics1.js & epics2.js

How should I enable the epics to set and access the sharedVariable when they are located on different files?

Thanks in advance!


Solution

  • Sounds like good case for DI: docs

    const sharedVariable = {} // can not be primitive type
    const epicMiddleware = createEpicMiddleware({
      dependencies: { sharedVariable }
    });
    
    const epic2 = (action$, state$, { sharedVariable }) => {
     // Rest of code
    }