0

I'm developing an IOS application on SwiftUI where a user can join groups and interact with other users, and I'm curious what the consequences of utilizing an ObservableObject singleton class for the current user's session are, which would directly replace a typical EnvironmentObject used in the same way. What I'm trying to do is eliminate directly injecting the EnvObj view model into subsequent view models.

So instead of this (which occurs in many places throughout the app):

class ChildViewModel: ObservableObject { 
    let session: SessionViewModel

    init(session: SessionViewModel, ...) { 
        self.session = session
        ...
    }

    ...
}

It would become:

class ChildViewModel: ObservableObject {
    let session = Session.shared

    init(...) { ... }

}

where Session is something like:

class Session: ObservableObject { 
    @Published var user: User?
    @Published var usersGroups: [GroupModel] = []

    // As singleton
    static let shared = Session()
    private init() { }

    // As environmentObject - Initialized after user is authenticated
    init() { 
        ...
        fetchUsersGroups()
    }

    func fetchUsersGroups() async { 

    }
}

If I know that the user will be defined by this point when the ChildViewModel is initialized, I figure I can create this singleton class which I can pull anywhere within the app after the user is logged in.

What issues would this implementation create?

corbiter
  • 47
  • 6
  • Nested `ObservableObject`s don't propagate their `@Published` changes unless you manually call `objectWillChange` on the parent. – jnpdx Dec 27 '21 at 22:37
  • 1
    @jnpdx I did not know that, thanks for the info. However in my use cases I really only use it to reference a certain property from `Session`, for example comparing the current user's (from `Session`) id with another's. I think creating this singleton object accessible everywhere is much easier than passing the user as an initializer (which is passed in from a `@StateObject` initializer in the view itself ... this can be hard refactoring especially when almost every view has this pattern). With this in mind, do you still see any issues worth considering? – corbiter Dec 28 '21 at 00:30
  • 1
    One of the answers to this part of your question "What issues would this implementation create" is you're going to make your ViewModels untestable if you're using a singleton object with all of them. Your session object should be injectable. – Anwuna Dec 28 '21 at 01:56

0 Answers0