In my view controller I have the following code:
func handleCommentPost() {
print("Handle post comment")
if !self.customView.textView.text.isEmpty {
if let comment = self.customView.textView.text {
self.viewModel.createPostComment(postItem: postItem, user: self.user, comment: comment) { result in
switch result {
case .success(_):
self.customView.textView.text = ""
self.datasource.applySnapshot(with: self.viewModel.postDetailItems.value)
self.customView.textView.resignFirstResponder()
case .failure(let error):
print("Failed to save comment: \(error)")
}
}
}
}
}
and in my viewModel createPostComment is defined as:
func createPostComment(postItem: PostItem, user: User, comment: String, completion: @escaping (Swift.Result<Comment, Error>) -> ()) {
let userId = user.id
let postId = postItem.post.id
let timestamp = Int(Date().timeIntervalSince1970)
let comment = Comment(postId: postId, userId: userId, comment: comment, createdTimestamp: timestamp)
firstly {
self.appViewModel.servicesProtocol.createComment(comment: comment)
}.done { comment in
let postDetail = PostDetailItem(comment: comment, like: nil, user: self.appViewModel.currentUser.value!)
self.postDetailItems.value.insert(postDetail, at: 0)
completion(.success(comment))
}.catch { error in
completion(.failure(error))
print("Error creating comment: \(error)")
}
}
As you can see I am using completion handlers to let my controller know - from a design perspective is this ok? As you may have noticed, the properties are Combine subject properties because I was toying with the idea of subscribing to the changes rather than completion handlers, but I don't know what the right approach is here.
It feels like the completion handlers are very easy to read and understand whereas using something like Combine to notify the controller is a lot of "magic", and might be hard to follow?
Aucun commentaire:
Enregistrer un commentaire