Taehyeon-Kim / Taehyeon-Kim.github.io

The life of recording is unbreakable
https://taehyeon-kim.github.io
MIT License
1 stars 0 forks source link

TCA101: WithViewStore #16

Open Taehyeon-Kim opened 10 months ago

Taehyeon-Kim commented 10 months ago

WithViewStore

View Builder가 상태를 관찰할 수 있도록 Store를 ViewStore로 변환하는 Helper Struct

Usage

private let store: StoreOf<Feature>

var body: some View {
  WithViewStore(self.store, observe: { $0 }) {
    // your view
  }
}

보통 위와 같은 형태로 많이 코드를 작성하는 것 같다.

struct ProfileView: View {
  let store: StoreOf<Profile>
  @ObservedObject var viewStore: ViewStoreOf<Profile>

  init(store: StoreOf<Profile>) {
    self.store = store
    self.viewStore = ViewStore(store, observe: { $0 })
  }

  var body: some View {
    Text("\(self.viewStore.username)")
    // ...
  }
}

공식 문서를 보면 WithViewStore를 사용하지 않고 이니셜라이저에서 수동으로 store를 관찰할 수 있도록 해줄 수도 있다고 한다. 복잡한 뷰를 래핑할 때는 컴파일러 성능과 진단이 저하될 수 있다고 하니 수동으로 설정하는 것이 더 나은 선택지일 수 있다.

Performance

1. store.scope, SceneState

2. 뷰가 Store의 어떤 상태에도 접근할 필요 없이 액션만 보낼 수 있어야 하는 경우

Button("Tap me") {
  ViewStore(self.store).send(.buttonTapped)
}

Links: