1
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Apr 28, 2019 at 15:39
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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

answered May 12, 2019 at 20:04
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.