DEV Community

Cover image for Redux-like state container in SwiftUI. Reducer composition.
Sergey Leschev
Sergey Leschev

Posted on • Edited on

Redux-like state container in SwiftUI. Reducer composition.

Important component of Redux-like state container is Reducer. We can extract and compose it as we do with state struct. It will allow us to respect a Single Responsibility principle and keep our reducers small and clean.

enum AppAction {
    case calendar(action: CalendarAction)
    case trends(action: TrendsAction)
}

func trendsReducer(
    state: inout TrendsState,
    action: TrendsAction
) -> AnyPublisher<TrendsAction, Never> {
    // Implement your state changes here
}

func calendarReducer(
    state: inout CalendarState,
    action: CalendarAction
) -> AnyPublisher<CalendarAction, Never>{
    // Implement your state changes here
}

func appReducer(
    state: inout AppState,
    action: AppAction
) -> AnyPublisher<AppAction, Never> {
    switch action {
    case let .calendar(action):
        return calendarReducer(&state.calendar, action)
            .map(AppAction.calendar)
            .eraseToAnyPublisher()
    case let .trends(action):
        trendsReducer(&state.trends, action)
            .map(AppAction.trends)
            .eraseToAnyPublisher()
    }

    return Empty().eraseToAnyPublisher()
}
Enter fullscreen mode Exit fullscreen mode

Redux provides a single source of truth, which eliminates tons of bugs produced by multiple states across the app. Best practices. Normalization and composition keep our app state simple and maintainable.


Contacts
I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.

πŸ›©οΈ #startups #management #cto #swift #typescript #database
πŸ“§ Email: sergey.leschev@gmail.com
πŸ‘‹ LinkedIn: https://linkedin.com/in/sergeyleschev/
πŸ‘‹ LeetCode: https://leetcode.com/sergeyleschev/
πŸ‘‹ Twitter: https://twitter.com/sergeyleschev
πŸ‘‹ Github: https://github.com/sergeyleschev
🌎 Website: https://sergeyleschev.github.io
🌎 Reddit: https://reddit.com/user/sergeyleschev
🌎 Quora: https://quora.com/sergey-leschev
🌎 Medium: https://medium.com/@sergeyleschev

Top comments (0)