0

I have a method which does processing for the events I receive from the server. The method can be called from multiple places in different classes. I want to synchronize the processing of the events using DispatchQueue/Serial Queue to discard the duplicate events in multiple calls. I know about dispatch queues and how it works but I am unable to find the best solution for my problem.

To achieve: By synchronizing I want to ensure sequential processing, to discard duplicate events.

func process(events:[Events]) {
  // by synchronizing I want to ensure sequential processing, to discard duplicate events 
  for event in events {
    // process, save to db, 
  }
  // issue notifications, etc 
}

class A {
  process(events)
}

class B {
  process(events)
}

Any help is appreciated. Thanks!

hacker_1989
  • 303
  • 4
  • 15
  • 1
    I don't think dispatch groups have anything to do with the solution. If you want to serialize the work performed, to give a chance for each call to query which events have already been processed, then use a serial queue. – Avi May 03 '18 at 18:03
  • Yea. I guess I wanted to mention dispatch queue, but I got confused, can you provide a solution to this @Avi ? I have edited my question. – hacker_1989 May 03 '18 at 18:08

1 Answers1

0

Try something like this:

class Event {
    let id: String = ""
}

class EventManager {
    static let shared = EventManager()

    private let processQueue = DispatchQueue(label: "processQueue")
    private var processedEvents = [Event]()

    private init() {}

    func process(events:[Event]) {
        processQueue.async { [unowned self] in
            for event in events {
                if !self.processedEvents.contains(where: { $0.id == event.id }) {
                    // process, save to db,
                    self.processedEvents.append(event)
                }
            }
            // issue notifications, etc
        }
    }
}
Jake
  • 13,097
  • 9
  • 44
  • 73
  • I would make sure `Event` is equatable and comparable and use a `Set` instead of an `Array`. Otherwise, this what I suggested in my comment on the question. – Avi May 03 '18 at 18:11