Usable lifecycle guarantees for SwiftUI.
onAppear
-> onLive
task
-> whileLive
- Add
swiftui-on-live
as a Swift Package Manager dependency. import onLive
within your view's file.- Replace your view's
onAppear
andtask
calls withonLive
andwhileLive
.
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
(replacingonAppear
) andwhileLive
(replacingtask
) are called exactly once.whileLive
's long running behaviors (like subscriptions intask
) are cancelled once, after permanent view removal.
This demo can be run from the repo with swift run Example