ReactiveSwift:如何重新绑定(删除旧绑定,添加新的)?

时间:2017-05-31 15:04:29

标签: swift reactive-swift

我有一个视图必须能够定期重新绑定到新的视图模型:这意味着删除旧的绑定以及连接新的绑定。我有一个可行的解决方案,但它不是线程安全的,我想知道是否有更惯用的方法来做同样的事情:

var disposeBag = CompositeDisposable()

func bind(viewModel: TopicProgressViewModel) {
    disposeBag.dispose()
    disposeBag = CompositeDisposable()

    disposeBag += self.reactive.isHidden <~ viewModel.isHidden
    disposeBag += height <~ viewModel.height
    disposeBag += label.reactive.text <~ viewModel.label
    disposeBag += progress.reactive.progress <~ viewModel.progressFraction
}

2 个答案:

答案 0 :(得分:2)

您应该使用SerialDisposable

var dispose = SerialDisposable()

func bind(viewModel: TopicProgressViewModel) {
    var disposeBag = CompositeDisposable()
    // serialDisposable will automatic dispose previous inner disposable
    dispose.inner = disposeBag
    disposeBag += self.reactive.isHidden <~ viewModel.isHidden
    disposeBag += height <~ viewModel.height
    disposeBag += label.reactive.text <~ viewModel.label
    disposeBag += progress.reactive.progress <~ viewModel.progressFraction
}

答案 1 :(得分:0)

您可以尝试使用scan序列化与信号的绑定,以维持当前的绑定状态。也许是这样的:

class TopicProgressView {
    private let bindInput: Observer<TopicProgressViewModel, NoError>
    private let bindSignal: Signal<CompositeDisposable, NoError>

    init() {
        private let (signal, observer) = Signal<TopicProgressViewModel, NoError>.pipe()

        bindInput = observer

        bindSignal = signal
            .scan(CompositeDisposable()) { [unowned self] disposeBag, newViewModel in
                disposeBag.dispose()

                let newDisposeBag = CompositeDisposable()

                newDisposeBag += self.reactive.isHidden <~ newViewModel.isHidden
                newDisposeBag += self.height <~ newViewModel.height
                newDisposeBag += self.label.reactive.text <~ newViewModel.label
                newDisposeBag += self.progress.reactive.progress <~ newViewModel.progressFraction

                return newDisposeBag
            }
    }

    func bind(viewModel: TopicProgressViewModel) {
        bindInput.send(value: viewModel)
    }
}

(我没试过这个,但对我来说似乎是可行的)。