使用 RxCocoa 处理行选择的问题

Problem with handling row selection with RxCocoa

我正在研究用于 UITableView 的 RxCocoa。显示单元格一切正常,但是当我添加一个闭包来处理行选择时,会出现延迟。我的意思是,当我点击第一行时,什么也没有发生,当我点击第二行时,关闭显示我对第一行、第三行 - 第二行等的预期反应...... 请查看我的代码并帮助我解决问题。

import RxCocoa
import RxRelay
import RxSwift
import UIKit

final class ListViewController: UITableViewController {
    
    private var todos = BehaviorRelay<[String]>(value: ["Clean the apt", "Learn to code", "Call mom", "Do the workout", "Call customers"])
    let bag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "RxTodoList"
        tableView.dataSource = nil
        tableView.delegate = nil
        
        todos
            .bind(to: tableView.rx.items) { (tableView, row, element) in
                let cell = tableView.dequeueReusableCell(withIdentifier: "TodoCell")!
                cell.textLabel?.text = "\(element)"
                return cell
            }
            .disposed(by: bag)
        
        tableView.rx
            .modelDeselected(String.self)
            .asObservable()
            .subscribe(onNext: { [weak self] todo in
                print(todo)
            })
            .disposed(by: bag)
    }
    
}

您正在使用 modelDeselected 而不是 modelSelected

此外,您永远不应该将 Subject、Relay 或 Observable 作为 var,它们应该始终是 let。所以 var todos = BehaviorRelay... 应该是 let todos = BehaviorRelay...

最后:

The usage of subjects [and relays] should largely remain in the realms of samples and testing. Subjects are a great way to get started with Rx. They reduce the learning curve for new developers, however they pose several concerns...

-- (IntroToRx)