Seemed like a pretty straightforward question to ask but I can't find the answer anywhere. Maybe I'm wording it wrong. I simply want to know if I can initialize/run a function ONCE per session. For example, I want this HomeViewModel to run fetchSongs() (a function that fetches data from Firebase) when I first open the app and not again until I force close it or manually initialize it. Currently it is initializing every time the HomeView appears, which is pointlessly fetching and reloading the data over and over. What is the best way I should go about accomplishing this? Any help would be appreciated.
class HomeViewModel: ObservableObject {
@Published var songs = [Song]()
init() {
fetchSongs()
}
}
struct HomeView(): View {
@ObservedObject private var viewModel = HomeViewModel()
var body: some View {
VStack {
ForEach(viewModel.songs) { song in
Text(song)
}
}
}
}
CodePudding user response:
You should use onSnapshot()
instead of getDocument
CodePudding user response:
Use StateObject wrapper instead, it will be initialised once for this view
struct HomeView(): View {
@StateObject private var viewModel = HomeViewModel() // << here !!
CodePudding user response:
The best way is to use task, e.g.
struct HomeView(): View {
@State var songs: [Song] = []
var body: some View {
List {
ForEach(songs) { song in
Text(song.title)
}
}
.task {
songs = await SongFetcher.fetchSongs()
}
}
}
The task will be run when the view appears and cancelled when it disappears. There is a variation that takes an id param that will cancel and rerun the task when the param changes.
And by the way, we don't use view model objects in SwiftUI you have to learn structs, state and binding for view data.