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"
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() -> 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 {
set.insert(element)
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.