RxSwift 使用数据收集

RxSwift using a data collection

这是我第一次使用 rxSwift

我一直在尝试使用 rxswift 来观察数据收集并据此更新视图,但我做错了

我做了一个计时器来向数据集合中添加一个项目,默认情况下从 1 个项目开始,但集合视图似乎没有更新。

import Foundation
import UIKit
import MaterialComponents
import RxSwift
import RxCocoa

class MainFeedViewController : BaseViewController
{
    var loveData: [FeedDataModel] = []
    var collectionData : Observable<[FeedDataModel]>? = nil

    var collectionView : UICollectionView? = nil
    var cellId = "FeedCollectionViewCell"

    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        loadDummyData()

        initCollectionView()

        self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .height, relatedBy: .equal, toItem: collectionView, attribute: .height, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .width, relatedBy: .equal, toItem: collectionView, attribute: .width, multiplier: 1, constant: 0))

    }

    private func initCollectionView()
    {
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout.init())
        collectionView!.register(UINib(nibName: cellId, bundle: nil), forCellWithReuseIdentifier: cellId)
        collectionView!.delegate = self
    //collectionView!.dataSource = self
        collectionView!.backgroundColor = UIColor.groupTableViewBackground
        collectionView?.translatesAutoresizingMaskIntoConstraints = false

        collectionData!.bind(to: collectionView!.rx.items(cellIdentifier: cellId))
        {
            _, data, cell in
            let a = cell as! FeedCollectionViewCell
            a.imgMAIN.downloaded(link: (data.image?.absoluteString)! )
            a.lblTitle.text = data.title

        }.disposed(by: disposeBag)

        collectionView?.rx.modelSelected(FeedDataModel.self).subscribe {
            next in
            }.disposed(by: disposeBag)

        self.view.addSubview(collectionView!)
    }

    override func viewDidAppear(_ animated: Bool)
    {
//        DispatchQueue.main.async {
//            self.collectionView?.reloadData()
//        }

        Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(addObj), userInfo: nil, repeats: true)
    }

    private func loadDummyData()
    {
        addObj()
        collectionData = Observable.just(loveData)
    }

    @objc func addObj()
    {
        let obj1 = FeedDataModel.init(image: "https://via.placeholder.com/150",title: "Placeholder")

        print("adding object")
        loveData.append(obj1)
    }

}

你能给我指出正确的方向吗?

谢谢

好的...

构造函数Observable.just(loveData) 将创建一个 Observable,该 Observable 发出一次数组然后完成。最终,您要做的是逐项列出所有会导致集合视图更改的输入,并将它们用作 collectionData Observable 的输入。

但是现在,为了让你的脚湿润,你可以只使用主题:

class MainFeedViewController : BaseViewController
{
    var loveData: [FeedDataModel] = []
    let collectionData = PublishSubject<[FeedDataModel]>()

// ...

collectionData.asObservable().bind(to: collectionView!.rx.items(cellIdentifier: cellId))

// ...

private func loadDummyData()
{
    addObj()
    collectionData.onNext(loveData)
}

@objc func addObj()
{
    let obj1 = FeedDataModel.init(image: "https://via.placeholder.com/150",title: "Placeholder")

    print("adding object")
    loveData.append(obj1)
    collectionData.onNext(loveData)
}

PublishSubject class 是最基本的主题类型。它同时充当 Observable 和 Observer。因此,您可以使用 onNext() 将值推送到其中,当您这样做时,它会将这些值发送给订阅或绑定到它的任何观察者。由于您的集合视图绑定到它,这意味着集合视图将在事件发出时接收它们。

但这仅仅是个开始!像这样使用 Subject 只是将命令式代码转换为 Rx 将您推向的声明式风格的一种方式。

为了充分利用该系统,您需要有一些不同的想法。而不是思考,"When the user does X, the app should do Y." 你将不得不更多地按照 "This output changes whenever these things happen."

的思路组织你的想法

也许这很简单,"The collection view should update from a network request whenever the user taps the refresh button. If the request fails, then don't update the list." 看起来像:

refreshButton.rx.tap
    .flatMap {
        getRequestResponse()
            .catchError { _ in Observable.empty() }
    }
    .bind(to: collectionView!.rx.items(cellIdentifier: cellId, cellType: FeedCollectionViewCell.self))  { _, data, cell in
        cell.imgMAIN.downloaded(link: (data.image?.absoluteString)! )
        cell.lblTitle.text = data.title
    }
    .disposed(by: disposeBag)

或者您的代码似乎想要什么,"The collection view should start with a single entry and receive an additional entry every 5 seconds." 看起来像:

Observable<Int>.interval(5, scheduler: MainScheduler.instance)
    .scan(into: [FeedDataModel.init(image: "https://via.placeholder.com/150",title: "Placeholder")]) { current, _ in
        current.append(FeedDataModel.init(image: "https://via.placeholder.com/150",title: "Placeholder"))
    }
    .bind(to: collectionView!.rx.items(cellIdentifier: cellId, cellType: FeedCollectionViewCell.self))  { _, data, cell in
        cell.imgMAIN.downloaded(link: (data.image?.absoluteString)! )
        cell.lblTitle.text = data.title
    }
    .disposed(by: disposeBag)