Skip to content

Instantly share code, notes, and snippets.

import SwiftUI
// This is an example of how to keep the ObservableObjects near the root of the view hierarchy
// and dispatch actions from any view easily without having to pass too many things down. This
// helps keep the views simple and makes previews a lot easier.
//
// This is inspired from what Apple is doing with `DismissAction`, `OpenURLAction`, `OpenWindowAction`, etc...
// The following is a very simple example with only two view-levels and we could pass closures directly,
@tclementdev
tclementdev / ActionsDispatcher.swift
Last active February 23, 2023 21:29
SwiftUI actions dispatcher
import SwiftUI
// NOTE: This is still unsatisfying as it does not support calling async, throwing and non-void returning actions.
// I'm still looking for something better, see another approach here:
// V2 -> https://gist.github.com/tclementdev/c402bf5fddd8570287874333bc45a474
struct ActionsDispatcher {
private struct Key: Hashable {
let action: Action
let objectIdentifier: ObjectIdentifier
@tclementdev
tclementdev / libdispatch-efficiency-tips.md
Last active April 16, 2024 01:02
Making efficient use of the libdispatch (GCD)

libdispatch efficiency tips

The libdispatch is one of the most misused API due to the way it was presented to us when it was introduced and for many years after that, and due to the confusing documentation and API. This page is a compilation of important things to know if you're going to use this library. Many references are available at the end of this document pointing to comments from Apple's very own libdispatch maintainer (Pierre Habouzit).

My take-aways are:

  • You should create very few, long-lived, well-defined queues. These queues should be seen as execution contexts in your program (gui, background work, ...) that benefit from executing in parallel. An important thing to note is that if these queues are all active at once, you will get as many threads running. In most apps, you probably do not need to create more than 3 or 4 queues.

  • Go serial first, and as you find performance bottle necks, measure why, and if concurrency helps, apply with care, always validating under system pressure. Reuse