I want to have multiple reducers acting on one "Entity" of my app. Just like @ngrx/store, otherwise my reducer will get way too big
Thanks
Heres a small snippet you can use to combine reducers that act on identical types:
func combineReducers<T>(_ first: @escaping Reducer<T>, _ remainder: Reducer<T>...) -> Reducer<T> {
return { action, state in
let firstResult = first(action, state)
let result = remainder.reduce(firstResult) { result, reducer in
return reducer(action, result)
}
return result
}
}
// Usage:
let reducer = combineReducers(first, second, third)
Interesting. What does your reducer setup look like to make you need this? I see the technical appeal, but I never got into that situation, yet, and suffer from FOMO :)
I can't how you the actual reducer because I would get fired, but imagine it like this, but with 50+ actions:
func counterReducer(action: Action, state: AppState?) -> AppState {
var state = state ?? AppState()
switch action {
case _ as SetUserRegionAction:
// Logic
case _ as SetUserNameAction:
// Logic
case _ as SetTradeAction:
// Logic
case _ as DeleteTradeAction:
// Logic
// ..More case goes here
default:
break
}
return state
}
Notice how the reducer has multiple entities, User and Trade.
Now imagine in an enterprise app where there are 20 of these entities with 5+ actions for each, which totals to 700+ lines long.
@dolanmiu Do you want to submit a PR to the docs, or prepare a Markdown Gist as a section we can paste into the guides, to explain this problem and its solution? It sounds useful and would be a shame to be buried in the issues list.
@mjarvis I'm curious, why treating differently the first and the others here? Not a rhetorical question, I'm wondering because I think I'm missing something.
@danielmartinprieto one needs the first in order to have a non-optional return type inside the reducer, as if we had only the variadic parameter, you could call it with zero reducers (combineReducer()), in which case the internal result type needs to be optional.
Ok, so it's a way of telling Swift "we need at least one reducer in order to provide the same Reducer signature".
Most helpful comment
Heres a small snippet you can use to combine reducers that act on identical types: