Group Group Group Group Group Group Group Group Group

Chapter 10 use of .merge().reduce() for EOEvents

Hello! I am going through chapter 10, and when doing parallel requests for Events, in the book, we are instructed to use .merge() and chaining a .reduce() like so:

static func events(forLast days: Int = 360) -> Observable<[EOEvent]> {
    let openEvents = events(forLast: days, closed: false)
    let closedEvents = events(forLast: days, closed: true)
    
    return Observable
      .of(openEvents, closedEvents)
      .merge()
      .reduce([]) { (running, new) -> [EOEvent] in
        running + new
      }
  }

What I don’t follow is why do we need to attach the reducer operator if the return of merge() will also be of type Observer<[EOEvent]>.

When I remove the reduce, I can see that the closure in combineLatest (where we combine categories and downloaded events) back in CategoriesViewController gets called twice, once with 0 events and then with all the events, but apart from that I cannot understand the difference.

I think a bit more of explanation on this would help me understand reduce and merge better. Thanks in advance for the help.

Hi,

As stated in the chapter, we are merging requests to run them in parallel. So, we need to accumulate the output of these two observables into one array. That’s why we use reduce. In other words, an array of both open and closed events will take place as we accumulate the separate outputs from the corresponding two observables.

Please note that there’s a bug in the code that’s shared for this chapter, that is, even though EOEvent.closeDate is an optional in the API response, it is being forced in the EOEvent.init method. Thus, open events never get parsed. To fix this, you can change try in closeDate = try? container.decode(Date.self, forKey: .closeDate) to try?.

This topic was automatically closed after 166 days. New replies are no longer allowed.