RxSwift 和 UICollectionView、UITableView

RxSwift and UICollectionView, UITableView

我有一个问题:如何使用 RxDataSources 在 Rx-way 中正确实现这样的场景:

我们有一个带有 UICollectionView(或 UITableView,在我的例子中是 collection 视图)的 class,结果不会立即出现,它们会在一段时间后异步出现。

我已经根据此处的教程实现了带有部分的模型: https://github.com/RxSwiftCommunity/RxDataSources

但数据仅创建一次 just 那里:

let sections = [
  SectionOfCustomData(header: "First section", items: [CustomData(anInt: 0, aString: "zero", aCGPoint: CGPoint.zero), CustomData(anInt: 1, aString: "one", aCGPoint: CGPoint(x: 1, y: 1)) ]),
  SectionOfCustomData(header: "Second section", items: [CustomData(anInt: 2, aString: "two", aCGPoint: CGPoint(x: 2, y: 2)), CustomData(anInt: 3, aString: "three", aCGPoint: CGPoint(x: 3, y: 3)) ])
]

Observable.just(sections)
  .bindTo(collectionView.rx.items(dataSource: dataSource))
  .addDisposableTo(disposeBag)

如果我的项目在一段时间后可用并且我希望我的 collection 视图自动更新,该怎么办?

感谢您的帮助。

您可以这样使用 Variable<[Section]>

enum Api {
    /// Network response
    static func call() -> Observable<[CustomData]> {
        return .just([CustomData(anInt: 0)])
    }
}

struct CustomData {
    let anInt: Int
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    typealias Section = SectionModel<String, CustomData>
    private let sections = Variable<[Section]>([])
    private let dataSource = RxTableViewSectionedReloadDataSource<Section>()
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        // change sections by api call
        Api.call()
            .map { (customDatas) -> [Section] in
                [Section(model: "First section", items: customDatas)]
            }.bindTo(sections)
            .addDisposableTo(disposeBag)

        sections.asDriver()
            .drive(tableView.rx.items(dataSource: dataSource))
            .addDisposableTo(disposeBag)

    }

    @IBAction func removeLastTableViewSection() {
        // or you can change the sections manually.
        sections.value.removeLast()
    }
}

当您更改 sections.value 时,UI 将自动更新。

希望对您有所帮助。