Reputation: 429
I'm using angular 2 with redux/store along with redux-observable to form epics. What I want to make is a general poller so I only need to write an the poller once. I have about 25 services and i'd rather have the action pass in what type of actions, and services it will execute then having the duplicate code and wrote huge case or if statements:
code i have so far:
startPoller: Epic<Action<void>, Action<void>> = action$ =>
action$.ofType(BankActions.DEPOSIT.POLL_DATA)
.switchMap(action =>
Observable.interval(1000)
.takeUntil(action$.ofType(BankActions.DEPOSIT.STOP_POLLING))
.mergeMap(count =>
this.bankService.getDeposit.(action.payload)
.map(payload => ({ type: BankActions.DEPOSIT.POLL_SUCCESS, payload }))
.catch(error => Observable.of({
type: BankActions.DEPOSIT.POLLING_FAILED,
payload: error
}))
)
)
What I want to do in pseudo code:
startPoller: Epic<Action<void>, Action<void>> = action$ =>
action$.ofType(BankActions.DEPOSIT.POLL_DATA || BankActions.WITHDRAW.POLL_DATA || InvestActions.STOCK_PRICE.POLL_DATA )
.switchMap(action =>
Observable.interval(1000)
.takeUntil(action$.ofType(action.STOP_POLLING))
.mergeMap(count =>
this.bankService.getDeposit(action.payload)
.map(payload => ({ type: BankActions.DEPOSIT.POLL_SUCCESS, payload }))
.catch(error => Observable.of({
type: BankActions.DEPOSIT.POLLING_FAILED,
payload: error
}))
)
)
I'm guessing to have it work I might need to make some type of base type that every action/service that needs to poll needs would extend then i could just check if that ifs of type 'PollerService' or type 'PollerEpic' and then I can filter on that?
Upvotes: 0
Views: 231
Reputation: 15401
It's a bit unclear what you're asking, but I think I can answer a few things.
Your pseudo code ofType
:
action$.ofType(BankActions.DEPOSIT.POLL_DATA || BankActions.WITHDRAW.POLL_DATA || InvestActions.STOCK_PRICE.POLL_DATA )
Can be accomplished by passing them as arguments; ofType
will check if a given action is of any of those types.
action$.ofType(BankActions.DEPOSIT.POLL_DATA, BankActions.WITHDRAW.POLL_DATA, InvestActions.STOCK_PRICE.POLL_DATA )
The next thing in your pseudo code I see is that you want the matched action to provide what STOP_POLLING
type.
.takeUntil(action$.ofType(action.STOP_POLLING))
It's unclear what values for STOP_POLLING
are acceptable, usually redux type variables should be named the same as the string e.g. STOP_POLLING = 'STOP_POLLING'
in which case it wouldn't matter as they'd all be the same 'STOP_POLLING'
value.
If you want them to vary, I wouldn't use the UPPER_CASE convention, cause that might make it confusing to maintain:
// what an action _might_ look like
{
type: BankActions.DEPOSIT.POLL_DATA,
meta: {
stopType: 'DEPOSIT_STOP_POLLING'
}
}
// then used something like this:
.takeUntil(action$.ofType(action.meta.stopType))
Upvotes: 1