选择表视图行时,do(onNext :)调用了两次

时间:2019-04-23 10:27:44

标签: ios swift uitableview uinavigationcontroller rx-swift

在RxSwift上选择表格视图行时遇到问题。有关详细信息,do(onNext :)函数上的代码被两次调用,因此也导致导航被两次按下。这是我在viewModel中的代码,请帮助我解决它。非常感谢。

struct Input {
    let loadTrigger: Driver<String>
    let searchTrigger: Driver<String>
    let selectMealTrigger: Driver<IndexPath>
}

struct Output {
    let mealList: Driver<[Meal]>
    let selectedMeal: Driver<Meal>
}

func transform(_ input: HomeViewModel.Input) -> HomeViewModel.Output {
    let popularMeals = input.loadTrigger
        .flatMap { _ in
            return self.useCase.getMealList()
            .asDriver(onErrorJustReturn: [])
    }

    let mealSearchList = input.searchTrigger
        .flatMap { text in
            return self.useCase.getMealSearchList(mealName: text)
            .asDriver(onErrorJustReturn: [])
    }

    let mealList = Observable.of(mealSearchList.asObservable(), popularMeals.asObservable()).merge().asDriver(onErrorJustReturn: [])

    let selectedMeal = input.selectMealTrigger
        .withLatestFrom(mealList) { $1[$0.row] }
        .do(onNext: { meal in
            self.navigator.toMealDetail(meal: meal)
        })

    return Output(mealList: mealList, selectedMeal: selectedMeal)
}

编辑:这是ViewController上的实现:

func bindViewModel() {
    self.tableView.delegate = nil
    self.tableView.dataSource = nil
    let emptyTrigger = searchBar
    .rx.text.orEmpty
    .filter { $0.isEmpty }
    .throttle(0.1, scheduler: MainScheduler.instance)
    .asDriver(onErrorJustReturn: "")

    let loadMealTrigger = Observable
    .of(emptyTrigger.asObservable(), Observable.just(("")))
    .merge()
    .asDriver(onErrorJustReturn: "")

    let searchTrigger = searchBar.rx.text.orEmpty.asDriver()
    .distinctUntilChanged()
    .filter {!$0.isEmpty }
    .throttle(0.1)

    let selectMealTrigger = tableView.rx.itemSelected.asDriver()

    let input = HomeViewModel.Input(
        loadTrigger: loadMealTrigger,
        searchTrigger: searchTrigger,
        selectMealTrigger: selectMealTrigger
    )

    let output = viewModel.transform(input)

        output.mealList
            .drive(tableView.rx.items(cellIdentifier: MealCell.cellIdentifier)) { index, meal, cell in
                let mealCell = cell as! MealCell
                mealCell.meal = meal
    }
    .disposed(by: bag)

    output.selectedMeal
    .drive()
    .disposed(by: bag)
    }

1 个答案:

答案 0 :(得分:0)

首先,这是RxSwift吗? 如果是这样,当您通过订阅收到新事件时,.do(onNext :)运算符会带来副作用。因此,在点击表行时将发生两个“反应”:1.订阅方法和2. .do(onNext :)事件。不幸的是,我对您的代码没有任何进一步的了解,因此可能还有其他东西也会导致该错误。 祝你好运!