2

I am trying to keep my publishers that would normally live in an ObservableObject viewModel in the view itself. How is it possible to use combine within the Init of the view struct? The key here is not to use ObservableObject, or @StateObject, or a viewModel at all. For instance this doesn't work below.

struct ContentView: View {
  
  @State private var boolOne = false
  @State private var boolTwo = false
  @State private var boolsBoth = false
  
  private var cancellables = Set<AnyCancellable>()
  
  init() {
  // dummy publisher that doesn't nothing, not the point of the question
    Publishers.CombineLatest($boolOne, $boolTwo)
      .receive(on: RunLoop.main)
      .map { boolOne, boolTwo -> Bool in
        return true
      }
      .removeDuplicates()
      .sink(receiveValue: { value in
        boolsBoth = value
      })
  }
  
  var body: some View {
    VStack {
      Text("Hello, world!")
    }
    .padding()
  }
}

I get an error "Generic struct 'CombineLatest' requires that 'Binding' conform to 'Publisher'" on line 20 here. I know this can be done, but I haven't done it, and mostly all tutorials online use a viewModel pattern as an ObservableObject. Do I have to create an AnyPublisher var somewhere first or use eraseToAnyPublisher somewhere?

5
  • 1
    This idea of "viewModel" in SwiftUI is made up nonsense. Get it out ya head! Commented Mar 30, 2023 at 1:32
  • 1
    The init of a strict gets reloaded and recreated many times. Doing any work there is not feasible. Only State and StateObjects can maintain Identity. Watch Demystify SwiftUI. Commented Mar 30, 2023 at 1:35
  • 1
    I feel like publishers aren't really meant to be used inside SwiftUI views. You might just want to use onChange. Is there any reason you want to avoid ObservableObject? Commented Mar 30, 2023 at 1:36
  • 1
    Don't fight the framework! That's exactly what view models are designed for. Commented Mar 30, 2023 at 4:49
  • Use the publisher in a .task modifier not in the init. Commented Mar 30, 2023 at 5:41

1 Answer 1

0

As Jessy commented this idea of "view model" in SwiftUI is made up nonsense. Just learn the View struct, it does this already. Eg

MyView(bool1, bool2)

MyView's body will be called if bool1 or bool2 is different from last time.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.