Search code examples
swiftcore-dataswiftuicombine

MVVM in SwiftUI and the appropriate Bindings


Edited

Having multiple data sources for an app

What is the best approach to combine all data sources together in one class and add it as one environment object, keeping in mind data might change, therefore objects update the views?

What are the appropriate Bindings to use for:

Services (API fetches): @Published?

Computed variables: Lazy var?

Please refer to the diagram as an example. Thanks.

These questions were good references:

An equivalent to computed properties using @Published in Swift Combine?

https://medium.com/genetec-tech/property-wrappers-in-swift-5-1-the-missing-published-implementation-1a466ebcf660

diagram

enter image description here


Solution

  • So, you should use a layered architecture and you will not have those problems.

    • service layer, it's the lowest layer reads the data from either web or db, or other services
    • repository layer gets the data from service and process it, caching, etc
    • usecase layer combines data from multiple repositories
    • viewmodel layer gets the data from usecase and sends it to view

    each service or repository handles one type of data "Users" for example

    now, if you need to combine multiple types of data, like Users and Companies let's say, you need a Usecase layer which will combine all the data

    on your viewmodel you only use the usecase layer

    One important note, passed objects change between layers, so on service layer you have UserDto (coming from webservice), and UserEntity (coming from DB), the repo will transform those in UserResponse, which you don't know if it's db or webservice and even more the UseCase will transform UserResponse and CompanyReponse into a User object which will be passed to ViewModel and will contain all data required there.

    Also, until you get to the viewmodel layer you should not need SwiftUI, if you need it, you are doing something wrong, use Swift Combine to handle data.