Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of type 'Observable<String>' has no member 'bind'

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>("")
like image 963
pankaj Avatar asked Feb 02 '18 07:02

pankaj


2 Answers

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)
like image 133
kodelit Avatar answered Nov 13 '22 03:11

kodelit


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")
like image 42
Valérian Avatar answered Nov 13 '22 02:11

Valérian