I am working on a screen which has segmented control and has 3 segments (year value 2019, 18, 17) and what I am doing is that on each segment click I have to reload data inside a tableview (getting data from an API request).

let purchaseResponse = inputs.selectedTab.map { index -> String in
        switch index {
        case 0:
            return "2019"
        case 1:
            return "2018"
        case 2:
            return "2017"
            return "2019"
        } }
        .flatMapLatest { year in
            return purchaseService.fetchPurchaseHistory(forYear: year, pageNumber: 1)

Right now this is what I have, and it works fine, as you can see I am using the Distinct operator which is like this:

extension Observable where Element: Hashable {

func distinct() -> Observable<Element> {
    var set = Set<Element>()
    return flatMap { element -> Observable<Element> in
        objc_sync_enter(self); defer {objc_sync_exit(self)}
        if set.contains(element) {
            return Observable<Element>.empty()
        } else {
            return Observable<Element>.just(element)

Can I somehow refactor this, or maybe use builtin operators? The reason to use Distinct was that if the user clicks a segment, next time it shouldn't get data from the API.


The operator you are looking for is distinctUntilChanged(). It skips only equal items followed one by one.

Or distinct() operator which skips the items what has been even once emitted in the sequence. In your case the fetchPurchaseHistory method could be triggered no more than 3 times by this observable with distinct operator


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.