Skip to content

SwiftUI view lifecycle operators — guaranteed to fire exactly once.

Notifications You must be signed in to change notification settings

adam-zethraeus/swiftui-onlive

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

onLive — SwiftUI lifecycle operators which fire exactly once.

Usable lifecycle guarantees for SwiftUI.

onAppear -> onLive
task -> whileLive

Usage

  1. Add swiftui-on-live as a Swift Package Manager dependency.
  2. import onLive within your view's file.
  3. Replace your view's onAppear and task calls with onLive and whileLive.

Why?

SwiftUI's standard view lifecycle methods are sometimes called repeatedly — making binding a behavior to your view's lifecycle much more complicated.

.task {
    for await payload in createWebsocketConnection() {
        // This subscription can be created multiple times.
    }
}

This demo shows onAppear, task, and task's cancellation behavior called repeatedly (within a LazyVStack — the simplest reproduction case).

Notice that:

  • onLive (replacing onAppear) and whileLive (replacing task) are called exactly once.
  • whileLive's long running behaviors (like subscriptions in task) are cancelled once, after permanent view removal.

This demo can be run from the repo with swift run Example

About

SwiftUI view lifecycle operators — guaranteed to fire exactly once.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages