BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

Is there anything wrong with supplying models with asynchronous functions in MVVM architecture?

Forums > SwiftUI

There are a few major models in my app, one of them being a user model:

struct User: Identifiable, Codable {
    var id = ""
    var name = ""
    // ...
}

I've been experimenting a bit with MVVM in my app and exploring ways to simplify the code, especially in the view models. One idea I had, for example, was to directly supply the models with an update() function, which is an async call to (obviously) update the model. Using Firebase's API as an example:

extension User {
    func update() {
        let db = Firestore.firestore()
        do {
            try db.collection("users").document(self.id)
                .setData(from: self)
        } catch {
            // Error handling ...
        }
    }
}

Hypothetically, I would also make create(), delete(), getSubcollectionXYZ() -> [XYZ] and other model-specific functions that I could offload from rather large view models.

I've tested it and it seems to work fine, but before I start making changes to my models and view models, I wanted to get the community's opinion on whether or not there are problems with this approach. I have a feeling that there are, given that I've never seen this done in MVVM, but I couldn't say for sure.

1      

As far as I can tell is that with MVVM is to leave the View with only code that required for it and remove as much of the logic to the View Model.

1      

In strict MVVM that would be applied different class, which would be the viewmodel class. User is a model, as you said.

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.