-2 C
New York
Friday, February 21, 2025

ios – Sharing information between view fashions?


Think about an app like Fb the place you create an account and might create posts.

I’ve two ObservableObject courses:

  1. AuthViewModel (used to deal with login and signup)
  2. ContentManager (used to deal with every little thing associated to posting content material)

ContentManager seems like this:

class ContentManager: ObservableObject {
    let contentService: ContentServiceProtocol
    non-public var cancellables = Set()
    
     var posts: [Post] = [] // holds the entire person’s posts
    
    init(contentService: ContentServiceProtocol) {
        self. contentService = contentService
    }
    
    func fetchAllPosts() {
        contentService.getAllPosts()
            .obtain(on: RunLoop.primary)
            .sink(receiveCompletion: { information in
                print("Acquired (information)")
        }, receiveValue: {[weak self] information in
            // Get the posts and replace the view mannequin
            self?.posts = information.information?. posts ?? []
        }).retailer(in: &cancellables)
    }

    func createPost() {
        // name endpoint to create a submit
    }

    // dozens of different features that decision the api

}

Now, within the AuthViewModel, I deal with login, signup, logout, and so on.

On profitable login, the API returns an array of the entire person’s posts:

class AuthViewModel: ObservableObject {
    let authService: AuthServiceProtocol
    non-public var cancellables = Set()
    
     var posts: [Post] = [] // holds all posts returned on login
    
    init(authService: AuthServiceProtocol) {
        self.authService  = authService
    }
    
    func login() {
        // login logic right here, disregarded for this query

        authService.login()
            .obtain(on: RunLoop.primary)
            .sink(receiveCompletion: { information in
                print("Acquired (information)")
        }, receiveValue: {[weak self] information in
            // Get the posts and replace the view mannequin
            self?.posts = information.information?. posts ?? []
        }).retailer(in: &cancellables)
    }
}

My drawback is that I don’t actually wish to maintain the posts contained in the AuthViewModel. I would like ContentManager to be the one supply of fact for the entire person’s posts.

Nevertheless, I’m unsure learn how to share the posts information from AuthViewModel to ContentManager.

I don’t assume calling ContentManager from AuthViewModel is the right manner, as that may make them too coupled.

However I don’t know the way else to do that.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles