The Synchronous RunLoop Pattern
The synchronous RunLoop pattern involves creating a new RunLoop, setting up a specified quit condition for it, then calling Run() on it to block the current thread until that quit condition is reached.
Use this pattern when:
You need to block the current thread until an event happens, and you have a way to get notified of that event, via a callback or observer interface or similar. A couple of common scenarios might be:
- Waiting for an asynchronous event (like a network request) to complete
- Waiting for an animation to finish
- Waiting for a page to have loaded
- Waiting for some call that requires a thread hop to complete
The fact that this blocks a thread means it is almost never appropriate outside test code.
Don't use this pattern when:
- You don't really need the entire thread to wait
- You don‘t have and can’t add a way to get notified when the event happens
- You're waiting for a timer to fire - for that, TaskEnvironment is likely a better fit.
Alternatives / see also: