滚动底部rxswift

时间:2019-06-02 14:39:37

标签: uitableview rx-swift moya

我在分页方面有问题... 当我尝试更改城市时,我的pageNumber + 1(但我设置为0)吗? 当我滚动底部时,viewModel.loadPartners()不起作用 有人帮我 我尝试向下滚动(在调试中打印很多“ 1111”)时尝试发送请求(仅当我的totalElements大于10时)

请检查我的“ tableView.rx.contentOffset”和viewmodel文件夹

我尝试使用此代码 https://jayeshkawli.ghost.io/swift-infinite-loading-items-in-collection-view/

在我尝试使用之前,但是还有很多额外的代码https://github.com/ReactiveX/RxSwift/blob/b3e888b4972d9bc76495dd74d30a8c7fad4b9395/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift#L42

我的代码是

    struct PartnersFilterCredentionals {
    let cityID:String
    let catID:String
    let pageNumber:String
}

     private let batchSize: Int = 10

    class PartnersViewModel: ViewModelProtocol {

    var productsCollection: Variable<[PartnersItem]>
    var currentBeginningIndex: Int
    var currentEndingIndex: Int
    var productsCount: Variable<Int>
    var loadingProducts: Variable<Bool>
    var pageLoadFinished: Variable<Bool>
    var currentPageNumber: Int

    struct Input {
        let fetchingPartners: AnyObserver<Void>;
        let cityID: AnyObserver<String>;
        let catID: AnyObserver<String>;
        let pageNumber: AnyObserver<String>;
    }



    struct Output {
        let partnersResultObservable: Observable<[PartnersItem]>;
        let errorsObservable: Observable<ErrorResponse>;
    }

    let input: Input;
    let output: Output;
    //Input
    private let fetchingPartnersSubject = PublishSubject<Void>();

    private let cityIDSubject = PublishSubject<String>();
    private let catIDSubject = PublishSubject<String>();
    private let pageNumberSubject = PublishSubject<String>();

    //Output
    private let partnersResultSubject = PublishSubject<[PartnersItem]>();
    private let errorSubject = PublishSubject<ErrorResponse>();

    let disposeBag = DisposeBag();
    var partnerService: PartnersService
    init(service: PartnersService) {
        input = Input(fetchingPartners: 

    fetchingPartnersSubject.asObserver(), cityID: cityIDSubject.asObserver(), catID: catIDSubject.asObserver(), pageNumber: pageNumberSubject.asObserver());
            partnerService = service
            output = Output(partnersResultObservable: partnersResultSubject.asObserver(), errorsObservable: errorSubject.asObserver());

        productsCollection = Variable([])
        currentBeginningIndex = 0
        currentEndingIndex = 0
        currentPageNumber = 0
        productsCount = Variable(0)
        pageLoadFinished = Variable(false)
        self.loadingProducts = Variable(false)

        loadPartners()
    }
    func loadPartners(){
        guard !loadingProducts.value else {return}
        self.loadingProducts.value = true


fetchingPartnersSubject.withLatestFrom(partnersFilterCredentionals).observeOn(ConcurrentMainScheduler.instance).flatMapLatest { credentials in
        return self.partnerService.fetchAllPartners(partnersFilterCredentionals: credentials).materialize()
            }.subscribe(onNext: { [weak self] event in
                switch event {
                case .next(let data):
                    let allProducts = data.retailList
                    self?.currentBeginningIndex = (self?.productsCollection.value.count)!
                    self?.currentEndingIndex = self!.currentBeginningIndex + data.retailList.count - 1
                    self?.productsCount.value = data.retailList.count
                    self?.productsCollection.value.append(contentsOf: allProducts)
                    self?.loadingProducts.value = false
                    self?.currentPageNumber += 1;
                    self?.pageLoadFinished.value = allProducts.count >= data.totalElements
                    self?.partnersResultSubject.onNext(allProducts);
                    break;
                case .error(let error):
                    self?.errorSubject.onNext(error as! ErrorResponse);
                    self?.loadingProducts.value = false
                    break;
                default:
                    break;
                }
            }).disposed(by: disposeBag);

    }




    private var partnersFilterCredentionals: Observable<PartnersFilterCredentionals> {
        return Observable.combineLatest(cityIDSubject.asObservable(), catIDSubject.asObservable(),pageNumberSubject.asObserver()) { cityID, catID , pageNumber in
            return PartnersFilterCredentionals(cityID: cityID, catID: catID,pageNumber: pageNumber);
        }
    }

}

// // 我的ViewController

    extension UIScrollView {
    func  isNearBottomEdge(edgeOffset: CGFloat = 20.0) -> Bool {
        return self.contentOffset.y + self.frame.size.height + edgeOffset > self.contentSize.height
    }
}
class PartnersViewController: PartnersGeneralViewController, ViewControllerSetupable, ViewControllerViewModelTypeProtocol, Stepper,UITableViewDelegate{

    private var catID: Int
    private var cityID: Int
    private var pageNumber: Int
    private var shouldShowLoadingCell = false
    var currentPage = 0
    typealias ViewModelType = PartnersViewModel
    let viewModel: ViewModelType
    private var regId = -1;
    private let tableView = UITableView()

    var numberOfItems: Int = 10
    var activityIndicatorView: UIActivityIndicatorView


    func setupSignals() {
        headerView.leftLogoButton.addTarget(self, action: #selector(closeFlow), for: .touchUpInside)
        filters()


        viewModel.output.partnersResultObservable
            .observeOn(mainScheduler)
            .bind(to: tableView.rx.items(cellIdentifier: PartnersCell.defaultReuseIdentifier, cellType: PartnersCell.self)) {
                row, element, cell in
                cell.update(with: element);
            }.disposed(by: viewModel.disposeBag);



        self.activityIndicatorView.hidesWhenStopped = true
        self.activityIndicatorView.startAnimating()
        _ = self.viewModel.output.partnersResultObservable.asObservable().observeOn(MainScheduler.instance).subscribe(onNext: { (partners) in
            print("\(self.viewModel.pageLoadFinished)")
            print("First index \(self.viewModel.currentBeginningIndex) last index \(self.viewModel.currentEndingIndex) products count \(self.viewModel.productsCollection.value.count)")
            self.tableView.performBatchUpdates({
                var indexPathsCollection: [IndexPath] = []
                if self.viewModel.currentBeginningIndex < self.viewModel.currentEndingIndex {
                    for i in self.viewModel.currentBeginningIndex...self.viewModel.currentEndingIndex {
                        indexPathsCollection.append(IndexPath(row: i, section: 0))
                    }
//                    self.tableView.insertRows(at: indexPathsCollection, with: .bottom)
                    self.tableView.reloadData()

                }
            }, completion: nil)
        })

        _ = Observable.combineLatest(self.viewModel.loadingProducts.asObservable(), self.viewModel.pageLoadFinished.asObservable()).observeOn(MainScheduler.instance).subscribe(onNext: { (loading, pageLoadFinished)in
            if loading == true && pageLoadFinished == false {
                self.activityIndicatorView.startAnimating()
            } else {
                self.activityIndicatorView.stopAnimating()
            }
        })

        tableView.rx.contentOffset
            .subscribe { _ in
                if self.tableView.isNearBottomEdge(edgeOffset: 10) && !self.viewModel.loadingProducts.value {
//                    self.viewModel.loadingProducts.value = true
                    self.viewModel.loadPartners()
                    print("1111")
                }
        }.disposed(by: disposeBag)


    }

    fileprivate func filters(){
        viewModel.input.catID.onNext(String(catID));
        viewModel.input.cityID.onNext(String(cityID));
        viewModel.input.pageNumber.onNext(String(self.viewModel.currentPageNumber))
        viewModel.input.fetchingPartners.onNext(());
        viewModel.currentBeginningIndex = 0
        viewModel.currentEndingIndex = 0
        viewModel.pageLoadFinished = Variable(false)
        viewModel.productsCollection = Variable([])
        tableView.reloadData()
    }

0 个答案:

没有答案