TCA Architecture in SwiftUI

Updated:

1. TCA 이란?

  • The Composable Architecture 의 약자로서 PointFree 에서 소개된 앱구조 라이브러리 입니다

TCA Official Github - https://github.com/pointfreeco/swift-composable-architecture

TCA는 단방향 Flow architecture 로써 단방형으로는 Redux, MVI, ReactorKit 과 같은 구조와 비슷한 Architecture 입니다.

2. TCA Diagram

image

  • 크게 2가지로 나누면 ViewStore 가 있고, 그 Store 안에는 Action, Reduce, State 이 있습니다

State

  • A type that describes the data your feature needs to perform its logic and render its UI.

  • 상태값인데 action 에 따라서 로직이 랜더되고 그것이 UI View 에 나타 내는것

Action

  • A type that represents all of the actions that can happen in your feature, such as user actions, notifications, event sources and more.

  • 상태와 연결되어 있는데 Action 은 State 에 어떠한 이벤트 동작을 가리킴

Reducer

  • A function that describes how to evolve the current state of the app to the next state given an action. The reducer is also responsible for returning any effects that should be run, such as API requests, which can be done by returning an Effect value.

  • 실제로 Action 들이 들어 왔을때, 상태를 어떻게 변경을 할 건지에 대해서 나옴 예시로 API 요청하면 Effect 을 return 을 함

Store

  • The runtime that actually drives your feature. You send all user actions to the store so that the store can run the reducer and effects, and you can observe state changes in the store so that you can update UI.

  • Store 가 View를 제외한 나머지부분을 관할한다고 보면됨. Store 를 통해서 Action 들이 들어오고, Reducer 를 통해서 비지니스 로직을 변경이 되면서 State 를 변경시킴 -> Store 에서 View로 UI 를 업데이트 시켜줌

데이터의 흐름은 다음과 같습니다.

  1. View 에서 어떠한 상태 변화나, 이벤트를 실행을 하게 되면 Action 에 신호를 전달합니다

  2. 그 이후에 Reduce 는 그 로직을 처리하고 결과 값을 State 에 넘겨 줍니다

  3. 그러면 새로운 State 값은 update 되어서 새로운 View 에 적용하게 됩니다

3. MVVM 과의 차이점

  • MVVM 을 ViewModel 이 State를 가지고 있다고 보면되는데, MVVM 자체로는 ViewModel 안에서 로직처리도 있지만, State 와 Action 들이 같이 묶여져 있지 않고 즉, 바인딩 되지 않아서 따로 논다는 점

  • TCA 는 스토어에서 종합적으로 로직, state, action 등을 하나로 종합적으로 처리한다는 것임. 쌍으로 묶어서 처리한다고 보면 됨

4. TCA 를 사용해야되는 이유?

  • Better State Management: State 를 View 에서 분리를 시켜서 Reduce function 에서만 State 를 변경할 수 있고, functional 하게 state 를 처리할 수 있다는 장점이 있고 -> 로직이 간결해짐

  • Easy to debug: 데이터의 흐름이 단방향이기 때문에 Reduce 함수 내부에서 Action 과 State 가 어떻게 처리되는지만 보기때문에 Debugging 이 쉬워짐 (양방향인 MVVM 같은경우 코드가 복잡해질때 debug 가 찾아내기가 어려움)

  • Enhance Testability: View 와 Logic 을 아예 분리 했기 때문에 Reduce 에 있는 로직만 test 하면되기때문에 Test 효과 향상됨

  • Modularization (Composability): Reduce 라는 것이 하나의 모듈로 분리를 할 수 있기 때문에 재사용 가능하게 reduce 를 사용할 수 있음


s

🗃 Reference

개발하는 정대리 - https://youtu.be/fYQ9YnbvasU

스위프트하이 - https://www.youtube.com/watch?v=vU_pRzQMoho

코드 스쿼드 - https://www.youtube.com/watch?v=2DO420E9lvs

Categories:

Updated:

Leave a comment