我设置了tableview并希望在数据更改时立即更新UI。我用调度器模拟数据更改。但问题是,表不会更新。有人能解释一下如何用RxSwift设置一个tableview来在数据更改时更新它的单元格吗?

  @IBOutlet private var tableView: UITableView!
  let europeanChocolates: Variable<[Chocolate]> = Variable([])
  let disposeBag = DisposeBag()

  //MARK: View Lifecycle

  override func viewDidLoad() {
    super.viewDidLoad()
    title = "Chocolate!!!"
    setupCellConfiguration()
    europeanChocolates.value = Chocolate.ofEurope
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
      var choclate = self.europeanChocolates.value[0]
      choclate.countryName = "Denmark"
    }

  }

  //MARK: Rx Setup

  private func setupCellConfiguration() {
    europeanChocolates.asObservable().bindTo(tableView.rx.items(cellIdentifier: ChocolateCell.Identifier, cellType: ChocolateCell.self)) {
      row, chocolate, cell in
      cell.configureWithChocolate(chocolate: chocolate)
    }
    .addDisposableTo(disposeBag)
  }

最佳答案

你没有提供巧克力的实现,但我假设它是结构,在这种情况下,你没有改变任何东西,因为

    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  var choclate = self.europeanChocolates.value[0]
  choclate.countryName = "Denmark"
}

你的欧洲巧克力被复制到新的var巧克力,但你永远不会保存它。你可以很容易地检查它,如果你尝试这个
  override func viewDidLoad() {
    super.viewDidLoad()
    title = "Chocolate!!!"
    setupCellConfiguration()
    europeanChocolates.value = Chocolate.ofEurope
    europeanChocolates.asObservable().subscribe(onNext: { choco in
        print("choco changed \(choco)")
    })
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
      var choclate = self.europeanChocolates.value[0]
      choclate.countryName = "Denmark"
    }

  }

我想不会印“巧克力换了”。如果我是对的,这会帮助你:
  override func viewDidLoad() {
    super.viewDidLoad()
    title = "Chocolate!!!"
    setupCellConfiguration()
    europeanChocolates.value = Chocolate.ofEurope
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
      var choclate = self.europeanChocolates.value[0]
      choclate.countryName = "Denmark"
      self.europeanChocolates.value[0] = choclate
    }

  }

如果没有帮助,请提供巧克力和巧克力细胞的实现

关于ios - RxSwift Observable不会在数据更改时更新tableview,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43914919/

10-09 10:00