2

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
Dubon Ya'ar
  • 349
  • 4
  • 13

1 Answers1

1

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"
user5082648
  • 11
  • 1
  • 3