Upgrade to Pro — share decks privately, control downloads, hide ads and more …

今更学ぶReSwift

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 今更学ぶReSwift

Avatar for Keisuke Kimura

Keisuke Kimura

October 25, 2020
Tweet

Other Decks in Programming

Transcript

  1. ͳͥࠓߋReSwift? • UIKit͔ΒSwiftUI΁ͷҠߦظʹೖΖ͏ͱ͢Δத UIKitͰ΋࢖͑ΔReduxܥͷϥΠϒϥϦΛ஌͓ͬͯ͘ͷ΋ѱ͘͸ͳ͍͔ͳͱࢥͬͯʂ • ReSwift͸ͦͦ͜͜ރΕͯΔϥΠϒϥϦ -> ࢖͍΍͍͢ • Swiftʹ͸ͪΌΜͱ௥ै͍ͯ͠Δ͙Β͍ͷ׆ൃ౓͸͋Δ

    • ͕͔͠͠ൃల΋Α͋͘Δ ຊՈReduxͷਐԽʹ௥ैͨ͠Γ͢Δ -> Redux-thunk͕ੜ·Εͨ͜ͱͰReSwift-thunk΋ੜ ·Εͨʢޙड़ʣ • TCA࢖͏ਓͱ͔ͷࢀߟʹͳΕ͹ͳ͙Β͍ͳؾ࣋ͪ
  2. import ReSwift struct AppState: StateType { var count = 0

    } // This action does not have state and is a mere marker of "X happened": enum CounterAction: Action { case increase case decrease } func appReducer(action: Action, state: AppState?) -> AppState { var state = state ?? AppState() if let counterAction = action as? CounterAction { switch counterAction { case .increase: state.counter += 1 case .decrease: state.counter -= 1 } } return state } let store = Store( reducer: appReducer, state: AppState(), middleware: []) store.dispatch(CounterAction.increase)
  3. import ReSwift import ReSwiftThunk // First, you create the middleware,

    which needs to know the type of your `State`. let thunkMiddleware: Middleware<AppState> = createThunkMiddleware() // Note that it can perfectly live with other middleware in the chain. let store = Store<AppState>(reducer: reducer, state: nil, middleware: [thunkMiddleware])
  4. // A thunk represents an action that can perform side

    effects, access the current state of the store, and dispatch new actions, as if it were a ReSwift middleware. let thunk = Thunk<AppState> { dispatch, getState in if getState!.loading { return } dispatch(RequestStart()) api.getSomething() { something in if something != nil { dispatch(RequestSuccess(something)) } else { dispatch(RequestError()) } } } // As the thunk type conforms to the `Action` protocol, you can dispatch it as usual, without having to implement an overload of the `dispatch` function inside the ReSwift library. store.dispatch(thunk)
  5. // A thunk can also be a function if you

    want to pass on parameters func thunkWithParams(_ identifier: Int) -> Thunk<AppState> { return Thunk<MyState> { dispatch, getState in guard let state = getState() else { return } if state.loading { return } api.getSomethingWithId(identifier) { something in if something != nil { dispatch(RequestSuccess(something)) } else { dispatch(RequestError()) } } } } // You can do the same with the Thunk that requires parameters, like so store.dispatch(thunkWithParams(10))