Skip to content

Instantly share code, notes, and snippets.

@kabiroberai
kabiroberai / Memoize.swift
Created December 21, 2023 14:18
Memoize your SwiftUI ViewModels
import SwiftUI
/// A view that initializes its associated `model` only once.
///
/// It's occasionally necessary to initialize a ViewModel-type object inside
/// a view body to pass along to a child view. `Memoize` allows you to
/// do this inline.
///
/// In the following example, `ChildViewModel.init` is only called once,
/// despite `MyView` being re-rendered every time the stepper value changes.
import Foundation
extension MainActor {
/// Invoke `body`, running synchronously if possible.
///
/// This method is equivalent to `Task { @MainActor in <body> }`, except that
/// the first thread hop is elided if the caller is already on the main thread.
/// Thus if `<foo>` has no subsequent thread hops, it can run fully synchronously.
@discardableResult
public static func runAsap<Success>(

Keybase proof

I hereby claim:

  • I am kabiroberai on github.
  • I am kabiroberai (https://keybase.io/kabiroberai) on keybase.
  • I have a public key ASBWpJ82Em53L7xqug2DlaLaph4XDKYpqFCxvmoXOznPPQo

To claim this, I am signing this object: