3

Siesta 如何处理分页 URL?是否有一种机制可以将多页结果作为单一资源进行管理?

4

1 回答 1

5

Siesta 没有为分页提供任何特殊处理。分页 URL 的行为与其他 URL 一样:每个 URL 都是唯一的资源。Siesta 没有任何黑魔法可以将来自不同 URL 的响应合并到一个资源中。

换句话说,如果您的分页方案看起来像/dingbats?page=3&per_page=10,则 Siesta 将“dingbats 的第 3 页,每页 10 个”视为单个资源。如果您的分页方案看起来像/dingbats?since_serial_num=31415&max=20,那么 Siesta 将有一个资源用于“自序列号 31415 以来最多 20 个 dingbats”。</p>

例子

这在实践中意味着什么?例如,假设您的 API 返回一个X-Next-Page标头(Github 分页方案的简化风格),并且您希望将结果合并到一个可无限滚动的表格视图中。

你可能会做这样的事情:

private var firstPageOfDingbats: Resource?
private var dingbats: [Dingbat] = []
private var dingbatsDisplayed: Int = 1

func resourceChanged(resource: Resource, event: ResourceEvent) {
  refreshPages()
}

func refreshPages() {
  // Naive implementation reconstructs the entire dingats array
  // with each update — which is probably just fine, since array
  // concatenation is cheap.

  dingbats.removeAll()

  var nextPage = firstPageOfDingbats
  while let curPage = nextPage {
    // This is a noop if data is up to date, but triggers a
    // that runs down the list if it needs updating.

    curPage.loadIfNeeded()

    // Assuming you’ve set up a content transformer to parse
    // the response as [Dingbat], you can pull them out of
    // the Resource cheaply.

    dingbats.appendContentsOf(
      curPage.contentAsType(ifNone: [Dingbat]()))

    // Don’t fetch everything if we’ve covered as far as the
    // user has scrolled.

    if dingbats.count >= dingbatsDisplayed {
      break
    }

    // If we have data and there’s another page, keep going!

    nextPage = curPage.optionalRelative(
      curPage.latestData?.header("X-Next-Page"))
  }

  tableView.reloadData()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return dingbats.count
}
// etc.

// Add code to increase dingbatsDisplayed and call refreshPages()
// when user scrolls to the bottom

如果已经存在数据并且一切都是最新的,Siesta 的缓存使得这种简单的页面遍历运行得非常快,但是当事情过时时会触发一连串的更新。

例如,如果您知道旧条目永远不会改变,而新条目只会出现在顶部,那么您可以进行更智能的数组更新。这取决于您使用的特定 API 以及它所做的保证。

绕过 Siesta 的缓存

If you have a sophisticated update scheme and want fine-grained control over exactly what’s requested and how results are held in memory, then you may want to bypass Siesta’s resource caching altogether. You don’t need to abandon Siesta to do that, however! To fall back to a more traditional request-based approach, use the Resource.request(…) methods instead of load() and loadIfNeeded():

paginatedResource.request(.GET).success { newData in … }

This lets you manage paginatedResource requests yourself, while still using Siesta’s caching for other parts of the API.

于 2015-12-28T17:40:06.417 回答