简体   繁体   中英

When using ReSwift with substates, how can I avoid receiving unwanted substate updates, when another substate is updated?

When using ReSwift with substates, how can i avoid receiving unwanted substate update ( SubstateA ), when updating a another substate (SubstateB)

I though that was the whole point haven substates...

State.swift

struct MainState: StateType {
    var subStateA: SubstateA?
    var subStateB: SubstateB?
}

struct SubstateA: StateType {
    let value: String
}

struct SubstateB: StateType {
    let value: String
}

Store.swift

let mainStore = ReSwift.Store<MainState>(reducer: { action, state -> MainState in

    var newState = state ?? MainState()

    switch action {

    case let anAction as UpdateSubstateA:
        newState.subStateA = newState.subStateA ?? SubstateA(value: anAction.value)

    case let anAction as UpdateSubstateB:
        newState.subStateB = newState.subStateB ?? SubstateB(value: anAction.value)

    default:
        break
    }
    return newState
}, state: nil)

Actions.swift

struct UpdateSubstateA: Action {
    let value:String
}

struct UpdateSubstateB: Action {
    let value:String
}

ViewController.swift

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {

        mainStore.subscribe(self)  { $0.select { state in (state.subStateB ) } }

        mainStore.dispatch(UpdateSubstateA(value: "a"))
        mainStore.dispatch(UpdateSubstateB(value: "b"))
    }
}

extension ViewController: StoreSubscriber {

    func newState(state: SubstateB?) {
        print("SubstateB updated")
    }

    typealias StoreSubscriberStateType = SubstateB?
}

Although I dispatched a single update action for SubstateB I also receive newState events when SubstateA is updated

Console

SubstateB updated
SubstateB updated
SubstateB updated

Question is old, but maybe an answer will be useful for somebody.

The subscription could be:

mainStore.subscribe(self)  { $0.select { $0.subStateB }.skipRepeats(==) }

SubstateB should conform to the Equatable protocol:

extension SubstateB: Equatable {
    static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.value == rhs.value
    }
}

Console:

SubstateB updated - nil (initial value)
SubstateB updated - value: "b"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM