swift 如何从网络代码更新ViewModel中的@Published变量?

nbnkbykc  于 2023-03-07  发布在  Swift
关注(0)|答案(1)|浏览(106)

我有这个(发射了3个同时网络呼叫)

class GenerationViewModel: ObservableObject {
  @Published var fetching1:Bool = false
  @Published var fetching2:Bool = false
  @Published var fetching3:Bool = false

  func go() {  
      let service1 = Service(??)  //what to pass here so that Service can update fetching1 only
      let service2 = Service(??) //what to pass here so that Service can update fetching2 only
      let service3 = Service(??) //what to pass here so that Service can update fetching3 only
  }
}

如何更新另一个类中已发布的变量?

lztngnrs

lztngnrs1#

一种方法是将self和一个密钥路径传递给Service,然后Service可以使用它写入由密钥路径指定的self的字段。

struct Service {
    let callback: (Bool) -> ()
    
    init<Object: AnyObject>(
        object: Object,
        keyPath: ReferenceWritableKeyPath<Object, Bool>
    ) {
        callback = {
            object[keyPath: keyPath] = $0
        }
    }
    
    func run() {
        Task { @MainActor in
            try? await Task.sleep(for: .seconds(1))
            callback(true)
        }
    }
}

我们可以这样使用它:

class GenerationViewModel: ObservableObject {
  @Published var fetching1:Bool = false
  @Published var fetching2:Bool = false
  @Published var fetching3:Bool = false

  func go() {  
    let service1 = Service(object: self, keyPath: \.fetching1)
    let service2 = Service(object: self, keyPath: \.fetching2)
    let service3 = Service(object: self, keyPath: \.fetching3)
    
    service1.run()
    service2.run()
    service3.run()
  }
}

相关问题