5
2

【TCA】observe(_:)でトラッキングしている値をクロージャ内で変化させた場合は変更を検知しない

Posted at

以下のコードで、ボタンをタップしたときにコンソールに出力される値はどうなるでしょうか?

// Feature
@Reducer
struct Feature {
    @ObservableState
    struct State {
        var flag = false
    }

    enum Action {
        case buttonTapped
        case finished
    }

    var body: some ReducerOf<Self> {
        Reduce { state, action in
            switch action {
            case .buttonTapped:
                state.flag = true
                return .none
            case .finished:
                state.flag = false
                return .none
            }
        }
    }
}

// ViewController
observe { [weak self] in
    guard let self else { return }
    print("flag: \(store.flag)")
    store.send(.finished)
}

正解はこうです。

flag: true

僕はてっきりこうなると思ってました。

flag: true
flag: false

TCAの内部は追ってないのでこうなりますよというだけの話ですが、地味にハマったのでしっかり理解しておきましょう。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2