0

I currently have a costly function (I already tried to optimise it as much as possible) and it needs to be called every time some random event happens, this creates 2 problems:

1) If the even happens (for example) 3 times in a row, the first two executions are going to be in the way, I thought using NSOperation to cancel every old execution and then start a new one so I'll always have the updated result, but that would create problem number 2

2) If during a period of time, the even happens regularly... I'll be always canceling old executions and the user will never see a result until the even stops happening for a while

What would be your suggestion for handling a situation like this?

mtet88
  • 524
  • 6
  • 21
  • 4
    problem number 2 is usually handled by _debouncing_. You don't trigger update unless some time passes between user actions. For example, when typing to a search field, you don't trigger search when text is changed but instead you plan action to happen in, e.g., 500 ms. When the user finishes typing for 500 ms, you trigger the update, possibly cancelling previous search. – Sulthan Jul 12 '19 at 16:30
  • 1
    Agreed; in the case of rapid requests, you need to decide whether you want to ignore the second request, or cancel the first request. You could of course come up with more elaborate answers like "cancel the first request if it's quite young, but finish it if it's been running for a while" (which is just debouncing coupled with cancelation). But it's up to you to decide what you want. I'd start by ignoring NSOperation or dispatch queues or computers entirely. What would you do if this were managed by people handing you request forms on paper? – Rob Napier Jul 12 '19 at 16:34
  • This sounds like the kind of thing the new Combine framework is equipped to handle. – matt Jul 12 '19 at 16:35
  • Any reactive framework will have something for debouncing. If you don't want to go that way, implementing the same using `Timer` is also simple. – Sulthan Jul 12 '19 at 16:42
  • @sulthan if you want, add your comment as an answer so I can accept it, thanks again – mtet88 Jul 12 '19 at 17:02

0 Answers0