0
votes

I have this setup: Parent View: PostsListView Child View: PostEditView

  • PostsListView shows a list short description of posts
  • On tap of any post, I present child view: PostEditView
  • Goal is to chage post here call API and when user comes back to PostsListView, it should show updated description

I'm using MVVM so, in PostsListView

@ObservedObject var viewModel : PostsListViewModel    
LazyVGrid(columns: columns) {
                    ForEach(viewModel.posts, id: \.self) { post in
                        NavigationLink(
                            destination: PostEditView(viewModel: PostEditViewModel(post: post))){
                                Text(post: post)
                                    .lineLimit(3)
                        }
                    }
                }

I pass view model(PostEditViewModel(post:)) to childView from parent view.

I'm not sure how to bind this 'post' object across both views' viewModels.

FYI viewModels:

PostsListViewModel:

class PostsListViewModel: ObservableObject{
    @Published var posts: [Post]
    //api operations....
}

PostEditViewModel:

class PostEditViewModel: ObservableObject{
    @Published var post: Post
    //custom Post mutation and api operations....
}
1

1 Answers

0
votes

You don't need to do any special Combine operations. Just make sure that Post is a reference type (class) and pass the Post instance from PostListViewModel.posts to PostEditViewModel.post, this way whenever you mutate any properties of the Post object in the child VM, the same changes will be reflected on the parent VM as well, since the Post object is a reference type and both VMs have a reference to the same object.