I am trying to bind a string value in ViewModel to a label in my ViewController but I am getting following error:
Value of type 'Observable' has no member 'bind' My code for binding in ViewController:
self.viewModel.myNum
        .map( { $0 })
        .bind(to: serialNumberLabel.rx.text)
myNum is defined in viewModel as following:
var myNum: Observable<String>
No I have 2 problems here: 1. Above error in ViewController 2. Initializing myNum in ViewModel I tried following for initializing myNum but I am getting error:
materialNum = Observable<String>("")
                I think that you might forget to use import RxCocoa.
For me the code works, but .map({ $0 }) is redundant because it returns the same value it gets, and you of course forgot to add .disposed(by:) at the end:
self.viewModel.myNum
    .bind(to: serialNumberLabel.rx.text)
    .disposed(by:self.disposeBag)
About the initialization you might do as Valérian said:
materialNum = Observable.just("My string")
But if you change observable later you will need again bind the label text.
EDIT: Example (author request)
@pankaj, I would recommend you to download RxSwift project from GitHub and check their playgrounds.
import RxSwift
import RxCocoa
class MyViewModel: ReactiveCompatible {
    fileprivate lazy var _text = BehaviorRelay<String>(value: "My Initial Text")
    var text: String {
        get { return _text.value }
        set { _text.accept(newValue) }
    }
}
extension Reactive where Base: MyViewModel {
    var text:Observable<String> {
        return base._text.asObservable()
    }
    var setText: AnyObserver<String> {
        return Binder<String>(base, binding: { viewModel, value in
            viewModel.text = value
        }).asObserver()
    }
}
Binder setText in Reactive extension above is not required in your case but may be useful in other cases.
Then you can bind:
self.viewModel.rx.text
    .bind(to: serialNumberLabel.rx.text)
    .disposed(by:self.disposeBag)
                        bind is for Relays (and Variable which is deprecated !).
Simply use subscribe
self.viewModel.myNum.subscribe(serialNumberLabel.rx.text)
You need to use one of the existing methods to create your observable:
materialNum = Observable.just("My string")
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With