kLike / ZhiHu-RxSwift

知乎日报 with RxSwift
371 stars 72 forks source link

你对Rx理解有不足。 #1

Closed roshanman closed 6 years ago

roshanman commented 7 years ago
extension HomeViewController {

    func loadData() {
        provider
            .request(.getNewsList)
            .mapModel(listModel.self)
            .subscribe(onNext: { (model) in
                self.dataArr.value = [SectionModel(model: model.date!, items: model.stories!)]
                self.newsDate = model.date!
                var arr = model.top_stories!
                arr.insert(arr.last!, at: 0)
                arr.append(arr[1])
                self.bannerView.imgUrlArr.value = arr
                self.pageControl.numberOfPages = model.top_stories!.count
                self.refreshView?.endRefresh()
            })
            .addDisposableTo(dispose)
    }
}

不要在代码里重复调用loadData,只需要调用一次来描述你的逻辑。 然后使用事件来驱动整个逻辑。 可以修改为如下:

// let loadDataEvent = PublishSubject<Void>()

    func loadData() {
        loadDataEvent
            .flatMap {
                self.provider
                    .request(.getNewsList)
                    .mapModel(listModel.self)
            }
            .subscribe(onNext: { (model) in
                self.dataArr.value = [SectionModel(model: model.date!, items: model.stories!)]
                self.newsDate = model.date!
                var arr = model.top_stories!
                arr.insert(arr.last!, at: 0)
                arr.append(arr[1])
                self.bannerView.imgUrlArr.value = arr
                self.pageControl.numberOfPages = model.top_stories!.count
                self.refreshView?.endRefresh()
            })
            .addDisposableTo(dispose)

当需要刷新数据的时候给loadDataEvent发送事件就可以驱动如下的代码。 loadDataEvent.onNext(())

kLike commented 7 years ago

多谢指教,学习啦,自己对rx确实只是刚学点皮毛,还有很多需要学习的地方,谢谢提醒