gpt4 book ai didi

ios - RxSwift 中的两种方式绑定(bind)

转载 作者:可可西里 更新时间:2023-11-01 03:03:19 26 4
gpt4 key购买 nike

我在 RxSwift 的示例代码中阅读了双向绑定(bind)运算符。

func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
let bindToUIDisposable = variable.asObservable()
.bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})

return StableCompositeDisposable.create(bindToUIDisposable, bindToVariable)
}

property改变时,它会通知变量,并设置变量的值,当变量的值被设置时,它会通知属性。我认为这会导致死循环...

最佳答案

我相信你可以使用 bindTo 🙂。以下是 ControlProperty <-> Variable 的实现和 Variable <-> Variable :

infix operator <-> { precedence 130 associativity left }

func <-><T: Comparable>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
let variableToProperty = variable.asObservable()
.distinctUntilChanged()
.bindTo(property)

let propertyToVariable = property
.distinctUntilChanged()
.bindTo(variable)

return StableCompositeDisposable.create(variableToProperty, propertyToVariable)
}

func <-><T: Comparable>(left: Variable<T>, right: Variable<T>) -> Disposable {
let leftToRight = left.asObservable()
.distinctUntilChanged()
.bindTo(right)

let rightToLeft = right.asObservable()
.distinctUntilChanged()
.bindTo(left)

return StableCompositeDisposable.create(leftToRight, rightToLeft)
}

ControlProperty <-> Variable 的例子(例如 UITextFieldUITextView )在 RxSwiftPlayer project

// Example of Variable <-> Variable

let disposeBag = DisposeBag()
let var1 = Variable(1)
let var2 = Variable(2)

(var1 <-> var2).addDisposableTo(disposeBag)

var1.value = 10
print(var2.value) // 10

var2.value = 20
print(var1.value) // 20

关于ios - RxSwift 中的两种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37496074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com