有没有更好的方法使用 Combine 分配数据

Is there a better way to assign data using Combine

我正处于理解 Combine 的初级阶段,令我惊讶的是我居然让这个简单的模型起作用了。在模型中,我只是使用 .receive 将数据传递给 init 中的 .receive 发布者。我想知道的是:

  1. 有没有更好的方法来实现这个功能
  2. None 在我添加 .store() 并传入 Set = [] 之前一直有效。据我了解,这是一种取消数据流的方法。但是虽然只是取消推流,但是没有它推流也是行不通的。想知道我的理解是否正确,是否有更好的方法来实现可取消。

    import SwiftUI
import Combine

struct ContentView: View {
    @ObservedObject var viewModel = SimpleViewModel()
    @State private var changer = ""
    
    var body: some View {
        VStack {
            TextField("ENTER TEXT TO PASS", text: $changer)
                .padding()
                .textFieldStyle(RoundedBorderTextFieldStyle())
            HStack(alignment: .top) {
                Button(action: {
                    viewModel.changer = self.changer
                }){
                    Text("Change")
                        .fontWeight(.bold)
                        .padding()
                        .foregroundColor(.white)
                        .background(Color.blue)
                        .cornerRadius(10)
                }
                VStack {
                    Button(action: {}){
                        Text("Receive")
                            .fontWeight(.bold)
                            .padding()
                            .foregroundColor(.white)
                            .background(Color.green)
                            .cornerRadius(10)
                    }
                    Group {
                        Text(viewModel.firstValue).bold()
                        Text(viewModel.secondValue).bold()
                        Text(viewModel.thirdValue).bold()
                    }.padding(.vertical)
                }

            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

    final class SimpleViewModel: ObservableObject {
    @Published var changer = ""
    @Published var firstValue = "Value #1"
    @Published var secondValue = "Value #2"
    @Published var thirdValue = "Value #3"
    
    private var cancellableSet: Set<AnyCancellable> = []
    
    init() {
       $changer
        .receive(on: RunLoop.main)
        .assign(to: \.firstValue, on: self)
        .store(in: &cancellableSet)
    }

}
                             

我假设在这种情况下您可以只使用 didSet,比如

final class SimpleViewModel: ObservableObject {
    @Published var changer = "" {
       didSet { firstValue = changer }
    }

    // ... other code
}