Stop repeating DispatchQueue.main.async

An efficient way to perform main queue operations for your iOS apps.

Krishnapalsinh Gohil
2 min readJul 1, 2023

How often do you find yourself adding this block in your code just so that the UI layer get convenience to update it’s components?

Let’s consider the scenario of a RemoteItemLoader and an ItemListController

Notice, how the RemoteItemLoader is given the responsibility to complete on main queue. It's not ideal for the API or the ItemListController to handle dispatching to the main queue. It’s not their responsibility, we need a better solution, and that's where the MainQueueDecorator comes in.

The MainQueueDecorator acts as an interface between the RemoteItemLoader and the ItemListController, providing a neat way to handle main queue operations.

First, we define the ItemService protocol, which allows us to decouple our code from the concrete implementation of the RemoteItemLoader. This also gives us the flexibility to intercept the service and modify its behavior, such as in our case dispatching to the main queue.

Next, we make the RemoteItemLoader conform to the ItemService protocol.

We then replace the concrete class with the ItemService protocol in the ItemListController. This decouples the controller from the implementation details and allows us to work with the abstraction.

To handle main queue operations, we implement the MainQueueDecorator and make it conform to the ItemService protocol. This decorator intercepts the service calls and ensures that the code execution is dispatched to the main queue.

Let’s see what we can do with ItemListController

With this setup, we can now guarantee that the code completes on the main queue, providing a clean and reliable way to handle UI updates. By decoupling the threading logic from the RemoteItemLoader and ItemListController, we improve the maintainability and testability of our codebase.

In summary, using a MainQueueDecorator to handle main queue operations is a great approach for managing UI updates in iOS apps. It promotes cleaner code, separation of concerns, and better code organisation.

Start implementing this pattern already! If you have any further questions or need additional assistance, feel free to ask.

If you found this article insightful, I highly recommend checking out my other articles. They can provide even more valuable information and insights. Thank you.

--

--