Reswift: How could i use multiple reducer in Reswift 4.0.0

Created on 27 Apr 2017  路  2Comments  路  Source: ReSwift/ReSwift

I am new to use reswift.i have a question now,how could i create multi reducers for a Store.Before reswift4.0,i saw "CombineReducer"

Question

Most helpful comment

There are many ways to create multiple reducers. I'll show a couple examples:

One way is to split the app reducer into sub-reducers for sections of state:

func appReducer(action: Action, state: AppState?) -> AppState {
    return AppState(
        foo: fooReducer(action: action, state: state?.foo),
        bar: barReducer(action: action, state: state?.bar)
    )
}

Another would be to split reducers according to the action:

func appReducer(action: Action, state: AppState?) -> AppState {
    switch action {
       case let action as FooAction: 
           return fooReducer(action: action, state: state)
       case let action as BarAction: 
           return barReducer(action: action, state: state)
    }
}

You could also make a combineReducer function if you wanted, that does combineReducers(fooReducer, barReducer) and works in a similar fashion to the second example above.

// note, pseudo-code, this will likely not compile
func combineReducers<S>(_ reducers: Reducer<S>...) -> Reducer<S> {
    return { action, state in
        for reducer in reducers {
            reducer(action, state)
        }
    }
}

All 2 comments

There are many ways to create multiple reducers. I'll show a couple examples:

One way is to split the app reducer into sub-reducers for sections of state:

func appReducer(action: Action, state: AppState?) -> AppState {
    return AppState(
        foo: fooReducer(action: action, state: state?.foo),
        bar: barReducer(action: action, state: state?.bar)
    )
}

Another would be to split reducers according to the action:

func appReducer(action: Action, state: AppState?) -> AppState {
    switch action {
       case let action as FooAction: 
           return fooReducer(action: action, state: state)
       case let action as BarAction: 
           return barReducer(action: action, state: state)
    }
}

You could also make a combineReducer function if you wanted, that does combineReducers(fooReducer, barReducer) and works in a similar fashion to the second example above.

// note, pseudo-code, this will likely not compile
func combineReducers<S>(_ reducers: Reducer<S>...) -> Reducer<S> {
    return { action, state in
        for reducer in reducers {
            reducer(action, state)
        }
    }
}

Closing this for now.

Was this page helpful?
0 / 5 - 0 ratings