肇鑫的技术博客

业精于勤,荒于嬉

Experiences of Adapting Semaphore to Async/Await of Poster 2

In 2.6.0, Poster 2 adopted its architecture from using Semaphore to Async/Await.

Semaphore

Poster 2 used to using semaphores in two parts when posting contents.

  1. Posting contents with multiple accounts.
  2. Posting multiple images when tweeting.

As all network operations are asynchronous, I used semaphores to order the operations one by one. But this architecture had a potential problem. When an error happened, the iterated operations wouldn't stop and the app freeze.

Besides, using semaphores with completions also made the code more complex to understand.

Async/Await

Poster 2 now adapts with Async/Await. It is a framework base on PromiseKit. When using Async/Await, the async code behaves like sync code. So you don't need to deal with completion handlers any more.

Benefits

  1. Async code runs as sync code. Easy to understand.
  2. Using do...try...catch, no completion handlers are needed.

Side Effects

  1. Async/Await blocks the main thread somehow. So you have to use async block for the very first calling or view animations won't work.
  2. Because of the previous reason, you have to deal with the cross-threading if you also using RealmSwift.
  3. Not all code could change to Async/Await. For example, some frameworks use delegates instead of completion handlers, like AVAudioPlayer.