1

我是 RxSwift 的新手,我想知道如何能够“被动地”使用 UIRefreshControl 和 UITableView 而不是创建目标的常规方式,并手动调用beginRefreshing()and endRefreshing()

例如,假设我正在从 API 加载一些字符串:

class TableViewController: UITableViewController {

    var data : [String] = []

    let db = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        refreshControl = UIRefreshControl()

        //I don't want to use
        //refreshControl?.addTarget(self, action: #selector(getData), forControlEvents: .ValueChanged)

        //Do something to refreshControl.rx_refreshing?
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        let str = data[indexPath.row]
        cell.textLabel?.text = str
        return cell
    }

    //MARK: - Requests

    private func getData() {
        let myData = MyAPI.getData() //Returns Observable<[String]>
        myData
            .subscribe({ [weak self] (event) in
                switch event {
                case .Next(let strings):
                    self?.data = strings
                    self?.tableView.reloadData()
                    break
                case .Error(let err):
                    print(err)
                    break
                case .Completed:
                    break
                }
                // self?.refreshControl?.endRefreshing()
                })
            .addDisposableTo(db)
    }
}

MyAPI发送对某些字符串值的请求,如何绑定refreshControl到调用getData()并在完成(或出错)网络请求时停止刷新?我需要绑定到refreshControl.rx_refreshing吗?

4

1 回答 1

8

RxSwift 的示例应用程序提供了一个有趣的类来处理这种逻辑:ActivityIndicator.

一旦ActivityIndicator进入,绑定rx_refreshing到请求的代码就变得非常简单。

let activityIndicator = ActivityIndicator()

override func viewDidLoad() {
  super.viewDidLoad()

  refreshControl = UIRefreshControl()

  // When refresh control emits .ValueChanged, start fetching data
  refreshControl.rx_controlEvent(.ValueChanged)
    .flatMapLatest { [unowned self] _ in
      return self.getData()
      .trackActivity(activityIndicator)
    }
    .subscribeNext { [unowned self] strings in
      self.data = strings
      self.tableView.reloadData()
    }
    .addDisposableTo(db)

  // Bind activity indicator true/false to rx_refreshing
  activityIndicator.asObservable()
    .bindTo(refreshControl.rx_refreshing)
    .addDisposableTo(db)
}

// getData only needs to return an observable, subscription is handled in viewDidLoad
private func getData() -> Observable<[String]> {
  return myData = MyAPI.getData() //Returns Observable<[String]>
}
于 2016-04-01T17:18:42.687 回答