micah
micah

Reputation: 1248

SwiftUI re-initialize EnvironmentObject?

How can I refresh an environment var in SwiftUI? It is easy to update any object that's a part of an environment object, but it seems like there should be a way to re-initialize.

struct reinitenviron: View{
    @EnvironmentObject private var globalObj: GlobalClass
    var body: some View{
        Text("refresh").onTapGesture {
            globalObj = GlobalClass() //error here
        }
    }
}

The following gives an error that globalObj is get only. Is it possible to re-initialize?

Upvotes: 1

Views: 190

Answers (1)

Asperi
Asperi

Reputation: 258441

A possible solution is to introduce explicit method in GlobalClass to reset it to initial state and use that method and in init and externally, like

class GlobalClass: ObservableObject {
  @Published var value: Int = 1

  init() {
    self.reset()
  }
  
  func reset() {
    self.value = 1
    // do other activity if needed
  }
}


struct reinitenviron: View{
    @EnvironmentObject private var globalObj: GlobalClass
    var body: some View{
        Text("refresh").onTapGesture {
            globalObj.reset()            // << here
        }
    }
}

Upvotes: 2

Related Questions