Skip to content

Control @Query auto-updates#18

Merged
groue merged 2 commits intomainfrom
dev/isAutoupdating
Apr 18, 2022
Merged

Control @Query auto-updates#18
groue merged 2 commits intomainfrom
dev/isAutoupdating

Conversation

@groue
Copy link
Copy Markdown
Owner

@groue groue commented Apr 18, 2022

By default, @Query automatically updates the database values for the whole duration of the presence of the view in the SwiftUI engine.

You can now spare resources by stopping auto-updates when the view disappears, and restarting them when the view appears. To do so, use the $players.isAutoupdating SwiftUI binding, as in the example below:

import GRDBQuery
import SwiftUI

struct PlayerList: View {
    @Query(PlayerRequest(), in: \.dbQueue)
    var players: [Player]
    
    var body: some View {
        List(players) { player in
            HStack {
                Text(player.name)
                Spacer()
                Text("\(player.score) points")
            }
        }
        // Stop observing the database when the view disappears,
        // and start again when the view appears.
        .mirrorAppearanceState(to: $players.isAutoupdating)
    }
}

This great idea was suggested by @davedelong. Thank you!

@groue groue merged commit 0bb2850 into main Apr 18, 2022
@groue groue deleted the dev/isAutoupdating branch April 18, 2022 08:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant