RxSwift中的可观察元素数组

时间:2017-08-24 06:25:01

标签: ios iphone rx-swift

我是RxSwift的新手,正在研究一些样品进行测试。我在RxSwift的帮助下在uitableview上显示了一些数据。但是当我尝试从tableview中删除任何项目并重新加载时。可观察数组没有更新,并且由于此滚动导致最后一个项目崩溃。下面是代码,请帮助我知道我做错了什么。

self.itemArray = NSMutableArray(objects: "First Item","Second Item","Third Item","Fourth Item","Fifth Item","Sixth Item","Seventh Item","Eight Item","Nineth Item","Tenth Item","Eleventh Item","Twelveth Item","Thirtheenth Item","Fourtheenth Item","Fifteenth Item","Sixteenth Item","Seventhenth Item","First Item","Second Item","Third Item","Fourth Item","Fifth Item","Sixth Item","Seventh Item","Eight Item","Nineth Item","Tenth Item","Eleventh Item","Twelveth Item","Thirtheenth Item","Fourtheenth Item","Fifteenth Item","Sixteenth Item","Seventhenth Item")


var seqValue = Observable.just(self.itemArray)
seqValue
    .bind(to: rxtableView.rx.items) { (tableView, row, seqValue) in
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
        cell.textLabel?.text = self.itemArray.object(at: row) as? String
        cell.backgroundColor = .clear
        return cell
    }.disposed(by: disposeBag)


self.rxtableView.rx.itemDeleted
    .subscribe(onNext: { [unowned self]indexPath in
        self.itemArray.removeObject(at: indexPath.row)
        seqValue = Observable.just(self.itemArray)
        self.rxtableView.reloadData()
    }).addDisposableTo(disposeBag)

2 个答案:

答案 0 :(得分:1)

使它成为BehaviorSubject,即 -

ReadMyData

而不是' seqValue = Observable.just(self.itemArray)'做

var seqValue = BehaviorSuject.create(self.itemArray)

调用' .reloadData()'没有必要

答案 1 :(得分:0)

我认为你想要的是RxSwift的Variable

let seqValue = Variable<String>(["First Item", ...])

所以你在.itemDeleted中可以修改那个变量:

seqValue.value.remove(at: indexPath.row)

VariableObservable,因此会自动传播更改。无需致电reloadData()