Calling API only once on changing segments 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 -&gt; String in
        switch index {
        case 0:
            return "2019"
        case 1:
            return "2018"
        case 2:
            return "2017"
        default:
            return "2019"
        } }
        .distinct()
        .flatMapLatest { year in
            return purchaseService.fetchPurchaseHistory(forYear: year, pageNumber: 1)
        }
        .trackActivity(inputs.indicator)
        .materialize()
        .share()


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() -&gt; Observable&lt;Element&gt; {
    var set = Set&lt;Element&gt;()
    return flatMap { element -&gt; Observable&lt;Element&gt; in
        objc_sync_enter(self); defer {objc_sync_exit(self)}
        if set.contains(element) {
            return Observable&lt;Element&gt;.empty()
        } else {
            set.insert(element)
            return Observable&lt;Element&gt;.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