RxSwift中的双向绑定

时间:2016-05-28 06:45:38

标签: ios swift functional-programming reactive-cocoa rx-swift

我在RxSwift的示例代码中读取了双向绑定运算符。

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发生变化时,它将通知变量,并设置变量的值,而变量的值设置后,它将通知属性。我认为这会导致无休止的循环......

6 个答案:

答案 0 :(得分:15)

我相信你可以使用bindTo。以下是ControlProperty <-> VariableVariable <-> 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

答案 1 :(得分:8)

感谢您提出问题,我花了一些时间来挖掘ControlProperty实现(请注意我已添加.debug()调用来跟踪为控件属性生成的值。)

public struct ControlProperty<PropertyType> : ControlPropertyType {
    public typealias E = PropertyType

    let _values: Observable<PropertyType>
    let _valueSink: AnyObserver<PropertyType>

    public init<V: ObservableType, S: ObserverType where E == V.E, E == S.E>(values: V, valueSink: S) {
        _values = values.debug("Control property values").subscribeOn(ConcurrentMainScheduler.instance)
        _valueSink = valueSink.asObserver()
    }

    public func on(event: Event<E>) {
        switch event {
        case .Error(let error):
            bindingErrorToInterface(error)
        case .Next:
            _valueSink.on(event)
        case .Completed:
            _valueSink.on(event)
        }
    }
}

我的测试设置如下,我已删除了所有位于此处的视图,以缩短其时间:

import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
    let variable = Variable<Bool>(false);
    let bag = DisposeBag();

    override func loadView() {
        super.loadView()

        let aSwitch = UISwitch();
        view.addSubview(aSwitch)

        (aSwitch.rx_value <-> variable).addDisposableTo(bag);

        let button = UIButton();
        button.rx_tap.subscribeNext { [weak self] in
            self?.variable.value = true;
        }.addDisposableTo(bag)
        view.addSubview(button);
    }
 }

infix operator <-> {
}

func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable{
    let bindToUIDisposable = variable.asObservable().debug("Variable values in bind")
    .bindTo(property)

    let bindToVariable = property
        .debug("Property values in bind")
        .subscribe(onNext: { n in
            variable.value = n
            }, onCompleted:  {
                 bindToUIDisposable.dispose()
        })

    return StableCompositeDisposable.create(bindToUIDisposable, bindToVariable)
 }

现在结果。首先我们尝试点击按钮,该按钮应将变量设置为true。这会在ControlProperty上触发on(event: Event<E>)并将切换值设置为true

2016-05-28 12:24:33.229: Variable values in bind -> Event Next(true)

// value flow
value assigned to Variable -> 
Variable emits event -> 
ControlProperty receives event -> 
value assigned to underlying control property (e.g. `on` for `UISwitch`)

接下来让我们触发开关。我们可以看到,控件在UIControlEventValueChanged生成了一个事件,该事件通过ControlProperty上的_values传递,然后将其值分配给Variable值,如上例所示。但是没有循环,因为更新Variable值并不会触发交换机上的控制事件。

2016-05-28 12:29:01.957: Control property values -> Event Next(false)
2016-05-28 12:29:01.957: Property values in bind -> Event Next(false)
2016-05-28 12:29:01.958: Variable values in bind -> Event Next(false)

// value flow
trigger the state of control (e.g. `UISwitch`) -> 
ControlProperty emits event -> 
value assigned to Variable -> 
Variable emits event -> 
ControlProperty receives event -> 
value assigned to underlying control property (e.g. `on` for `UISwitch`)

所以一个简单的解释是:

  • 一旦某种UIControlEvent被触发,就会发出控件的值
  • 当一个值直接分配给控件属性时,控件不会触发更改事件,因此没有循环。

希望它有所帮助,抱歉有点凌乱的解释 - 我已经通过实验找到了它)

答案 2 :(得分:3)

您键入的任何内容都会在5秒钟后清除。这是从answer

上方获取的
import UIKit
import RxSwift
import RxCocoa

class UserViewModel {
    let username = BehaviorSubject<String?>(value: "")
}

class ViewController: UIViewController {

    @IBOutlet weak var email: UITextField!

    var userViewModel = UserViewModel()
    let bag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        userViewModel.username.asObservable().subscribe { print($0) }.disposed(by: bag)
        (email.rx.text <-> userViewModel.username).disposed(by: bag)

        // clear value of the username.
        DispatchQueue.main.asyncAfter(deadline: .now()+5) {
            self.userViewModel.username.onNext(nil)
        }
    }
}

infix operator <->

@discardableResult func <-><T>(property: ControlProperty<T>, variable: BehaviorSubject<T>) -> Disposable {
    let variableToProperty = variable.asObservable()
        .bind(to: property)

    let propertyToVariable = property
        .subscribe(
            onNext: { variable.onNext($0) },
            onCompleted: { variableToProperty.dispose() }
    )

    return Disposables.create(variableToProperty, propertyToVariable)
}

答案 3 :(得分:1)

BehaviourRelay绑定回控件属性没有障碍。您只需要过滤具有相同值的事件(以防止无限循环)。

例如,对于我来说,我需要将电子邮件绑定到文本字段。但是我想在电子邮件输入过程中删除空格。 这是我如何实现的示例:

emailTextField.rx.text
  .map { $0?.trimmingCharacters(in: CharacterSet.whitespaces) } // remove whitespaces from input
  .bind(to: viewModel.email)
  .disposed(by: disposeBag)

// Just filter all events with no actual value change to prevent infinite loop
viewModel.email
  .filter { $0 != self.emailTextField.text } // if it removed whitespaces in mapping, values will not match and text in text field will be updated
  .bind(to: emailTextField.rx.text)
  .disposed(by: disposeBag)

答案 4 :(得分:0)

UITextField+Rx.swift中的源代码:

/// Reactive wrapper for `text` property.
    public var value: ControlProperty<String?> {
        return base.rx.controlPropertyWithDefaultEvents(
            getter: { textField in
                textField.text
            },
            setter: { textField, value in
                // This check is important because setting text value always clears control state
                // including marked text selection which is imporant for proper input 
                // when IME input method is used.
                if textField.text != value {
                    textField.text = value
                }

            }
        )
    }

魔咒在传教士中

if textField.text != value {
     textField.text = value
}

所以ControlProperty是通过两种方式绑定到变量的,

ControlProperty不会总是更改,因为使用setter方法的if判断。

我在RxSwift 5.0.1中签入

答案 5 :(得分:0)

@dengApro的答案非常接近。

UITextField+Rx.swift中的源代码:

 /// Reactive wrapper for `text` property.
    public var value: ControlProperty<String?> {
        return base.rx.controlPropertyWithDefaultEvents(
            getter: { textField in
                textField.text
            },
            setter: { textField, value in
                // This check is important because setting text value always clears control state
                // including marked text selection which is imporant for proper input 
                // when IME input method is used.
                if textField.text != value {
                    textField.text = value
                }
            }
        )
    }

由于textField,无法分配controlPropertyWithDefaultEvents

UIControl+Rx.swift中的源代码:

/// This is a separate method to better communicate to public consumers that
    /// an `editingEvent` needs to fire for control property to be updated.
    internal func controlPropertyWithDefaultEvents<T>(
        editingEvents: UIControl.Event = [.allEditingEvents, .valueChanged],
        getter: @escaping (Base) -> T,
        setter: @escaping (Base, T) -> Void
        ) -> ControlProperty<T> {
        return controlProperty(
            editingEvents: editingEvents,
            getter: getter,
            setter: setter
        )
    }

所以只有两个事件UIControl.Event = [.allEditingEvents, .valueChanged]可以观察到,

更改了变量,将变量绑定到ControlProperty,更改了ControlProperty并不是因为[.allEditingEvents, .valueChanged],然后完成了。

更改了ControlProperty,将ControlProperty绑定到Variable,将Variable更改并绑定到ControlProperty,将ControlProperty设置为不是由于[.allEditingEvents, .valueChanged]而引起的。


controlProperty的源代码中,将建立UIControl目标-操作。

[.allEditingEvents, .valueChanged]包含以下内容:editingDidBegin,editingChanged,editingDidEnd,editingDidEndOnExit,valueChanged,

因此直接分配给textField.text不会触发任何事件。