【问题标题】:Automatic UI updates with Apollo in Swift not working在 Swift 中使用 Apollo 自动更新 UI 不起作用
【发布时间】:2017-08-01 22:05:27
【问题描述】:

我有一个小型 Apollo iOS 应用程序的以下设置,我在表格视图中显示 会议 列表,并希望能够将 会议 添加到列表:

GraphQL

query AllConferences {
  allConferences {
    ...ConferenceDetails
  }
}

mutation CreateConference($name: String!, $city: String!, $year: String!) {
  createConference(name: $name, city: $city, year: $year) {
    ...ConferenceDetails
  }
}

fragment ConferenceDetails on Conference {
  id
  name
  city
  year
  attendees {
    ...AttendeeDetails
  }
}

fragment AttendeeDetails on Attendee {
  id
  name
  conferences {
    id
  }
}

ConferencesTableViewController

class ConferencesTableViewController: UITableViewController {

  var allConferencesWatcher: GraphQLQueryWatcher<AllConferencesQuery>?

  var conferences: [ConferenceDetails] = [] {
    didSet {
      tableView.reloadData()
    }
  }

  deinit {
    allConferencesWatcher?.cancel()
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    allConferencesWatcher = apollo.watch(query: AllConferencesQuery()) { result, error in
      print("Updating conferences: ", result?.data?.allConferences)
      guard let conferences = result?.data?.allConferences else {
        return
      }
      self.conferences = conferences.map { $0.fragments.conferenceDetails }
    }
  }

  // ...
  // standard implementation of UITableViewDelegate
  // ...

}

AddConferenceViewController

class AddConferenceViewController: UIViewController {

  // ... IBOutlets

  @IBAction func saveButtonPressed() {
    let name = nameTextField.text!
    let city = cityTextField.text!
    let year = yearTextField.text!

    apollo.perform(mutation: CreateConferenceMutation(name: name, city: city, year: year)) { result, error in
      if let _ = result?.data?.createConference {
        self.presentingViewController?.dismiss(animated: true)
      }
    }

  }
}

我还在 AppDelegate 中实现了cacheKeyForObject,如下所示:

apollo.cacheKeyForObject = { $0["id"] }

我的问题是是否可以通过此设置从自动 UI 更新中受益?当前执行CreateConferenceMutation 时,表视图不会更新。我是否遗漏了什么,或者我是否达到了docs 中提到的限制:

在某些情况下,仅使用 cacheKeyFromObject 不足以让您的应用程序 UI 正确更新。例如,如果您想在不重新获取整个列表的情况下将某些内容添加到对象列表中,或者如果您无法为某些对象分配对象标识符,则 Apollo 无法自动为您更新现有查询。

【问题讨论】:

    标签: ios swift graphql apollo apollo-ios


    【解决方案1】:

    这确实是自动 UI 更新的限制。虽然 Apollo 使用cacheKeyFromObject 通过 ID 匹配对象,并且涵盖了很多常见的情况,但它不能自动更新对象列表。

    在您的架构中,Apollo 无法知道应该将新添加的会议添加到 allConferences 列表中。它只知道allConferences 返回一个会议对象列表,但这些对象可以任意选择和排序。

    因此,在这种情况下,您必须自己从服务器重新获取查询,或者更改变异结果以包含更新后的列表。

    另一种选择是手动将新会议添加到客户端存储中的列表中。为此,下一版 Apollo iOS 将在 Apollo JavaScript 客户端中包含类似于 updateQueries 的手动更新选项。

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2017-07-18
      • 2018-11-09
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多