如何订阅观察@Published的函数?

时间:2020-07-13 07:08:50

标签: swiftui combine

需要在SwiftUI正文块中动态呈现消息列表:

 var chatSpace: some View {
        List(self.viewModel.getMessages(), id: \.self) { message in
            message
        }
 }

其中的视图模型是以下类的实例:

class MessagesListViewModel: ObservableObject {
    
    @ObservedObject var messageService: MessageService
    
    init(messageService: MessageService) {
        self.messageService = messageService
    }
    
    func getMessages() -> [MessageView] {
        return self.messageService.messages.map {
            return MessageView(message: $0)
        }
    }
    
    
}

我想在更新MessageService message属性时反映出更改,如何实现?我可以以某种方式订阅更改吗?现在,我基本上是通过更新messages发布的var添加一条消息,但是,它不会触发重新绘制

class MessageService: ObservableObject
{
    @Published var messages: [Message] = [Message]()
    
    func addMessage(_ sender: String, _ text: String, _ time: String) {
        self.messages.append(Message(sender: sender, text: text, time: time))
    }
}

1 个答案:

答案 0 :(得分:0)

现在,我基本上是通过更新已发布的消息var添加一条消息,但是它不会触发重新绘制

因为@ObservedObject var messageService: MessageServiceMessagesListViewModel中不执行任何操作,因为@ObservedObject被设计为在View中但不在View Model中。

所以解决方案应该像(消息的单独视图)

struct ChatSpace: some View {
   @ObservedObject var messageService: MessageService    // << view observes messages

   var body: some View {
      List(messageService.messages, id: \.self) {
            MessageView(message: $0)
      }
   }
}