Glenn Posadas
Glenn Posadas

Reputation: 13281

How to support distinctUntilChanged for Binder in RxSwift?

I made a simple Rx extension for FloatRatingView library for its rating property, like so:

import UIKit
import RxSwift
import RxCocoa

public extension Reactive where Base: FloatRatingView {

    /// Bindable sink for `rating` property
    public var rating: Binder<Double?> {
        return Binder(self.base) { frv, attr in
            frv.rating = attr ?? 0
        }
    }
}

Question is, how do I make that extension support the .distinctUntilChanged()?

My idea is I need to have a throttle or debounce before passing the value of the rating to the controller, like so:

    self.ratingView_Driver.rx.rating
        .distinctUntilChanged()
        .debounce(0.5, scheduler: MainScheduler.instance)
        .subscribe { _ in

        }.disposed(by: self.disposeBag)

Error is:

Value of type 'Binder' has no member 'distinctUntilChanged'

Upvotes: 0

Views: 1026

Answers (1)

SPatel
SPatel

Reputation: 4946

I assume that your view has rating property.

extension Reactive where Base: FloatRatingView {
    var rating: Observable< Double > {
        return self.observeWeakly(Double.self, #keyPath(FloatRatingView.rating)).map { $0 ?? 0 }
    }
}

Use:

self.ratingView.rx.rating
        .distinctUntilChanged()
        .debounce(0.5, scheduler: MainScheduler.instance)
        .subscribe { _ in

        }.disposed(by: self.disposeBag)

Upvotes: 1

Related Questions