这是我第一次使用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,它一次发出数组然后完成。最终,您要做的是逐项列出将导致集合视图更改的所有输入,并将它们用作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
类是最基本的主题类型。它既是Observable又是Observer。因此,您可以使用onNext()
将值推入其中,当您这样做时,它会将这些值发送给任何订阅或绑定它的观察者。由于您的集合视图绑定到它,这意味着集合视图将在发出事件时接收它们。
但这只是开始!使用像这样的主题只是将命令式代码转换为Rx推动你的声明式样式的一种方法。
为了充分利用系统,您必须有所不同。而不是思考,“当用户做X时,应用程序应该做Y.”你将不得不更多地按照以下方式组织你的想法:“只要这些事情发生,这个输出就会改变。”
也许这很简单,“只要用户点击刷新按钮,集合视图就应该从网络请求更新。如果请求失败,则不要更新列表。”看起来像这样:
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)
或者您的代码似乎想要什么,“集合视图应该以单个条目开始,并且每5秒钟接收一个额外的条目。”看起来像这样:
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)