Creating own observer for bind(to:)

Hi, in my custom cell I have something like this:

var title: String? {
    get {
        return titleLabel.text
    }
    set {
        titleLabel.text = newValue?.uppercased()
        titleLabel.addTextSpacing()
        // maybe something more
    }
}

and in order to use (in a reactive way) in my VC I have to use this long code

        viewModel
            .titleObs // Observable<String?>
            .subscribe(onNext: { title in
                cell.title = title
            })
            .addDisposableTo(cell.bag)

I’m not sure if it was in the book, maybe I missed it out, but is it possible to create a custom receiver for bind(to:) method? I know I can bind titleObs directly to titleLabel.rx.text, but I need to add some more work. even more, than I gave here in the example.
I would like to make something like this:

// VC
viewModel
    .titleObs // Observable<String?>
    .bind(to: cell.title)
    .addDisposableTo(cell.bag)

// Cell    
var title: Binder<String?> {
    titleLabel.text = newValue?.uppercased()
    titleLabel.addTextSpacing()
    // maybe something more
}

Ok i found solution, but I don’t know why I can’t delete the topic.

1 Like

Don’t worry about deleting the topic, let it stay so other who have similar questions can find it :slight_smile:

OK :blush:
@icanzilb can you explain why did you use .asObserver() and not leave UIBindingObserver just as is in your example? What’s the difference?

asObserver() returns an AnyObserver instance type erasing the actual observer implementation. So when you have a custom observer class of your own, let’s say MarinObserver you can’t use it with bind(to:) which expects AnyObserver (e.g. AnyObserver implements the minimal observer interface). That’s why when you return toObserver() you return type-erased observer which you can use for binding, but under the hood it’s still your custom observer that does the work.