Can I transform AnyPublisher to Published.Publisher?

Viewed 767

So I have a value of type AnyPublisher<Foo, Error> and I need to transform it to Published<Foo>.Publisher so that I can use it as @Published

so the idea is that I have a MVVM architecture

struct SwiftUIView: View {
  @ObservedObject var viewModel: MyViewModel
  var body: some View {
    Text(/*Foo has a title, how do I access it? */)
  }
  
}
class MyViewModel: ObservableObject {
  var cellModels: AnyPublisher<Foo, Error>
  // so the idea is to have and then access it in swiftUI view via viewModel.cellModels2.title
  @Published cellModels2 = convert_somehow_to_publisher(cellModels)
}

Apparently I cannot use viewModel.cellModels

Is that possible?

1 Answers

Looks like what you need is to have a Foo property on your view model, and update it using the AnyPublisher<Foo, Error> publisher that you have.

class MyViewModel: ObservableObject {

  var cellModels: AnyPublisher<Foo, Error> = ...
  private var cancellable: AnyCancellable?

  @Published var foo: Foo?

  init() {
    cancellable = cellModels.assign(to: \.foo, on: self)
  }
} 

Then you can access .foo in the view normally:

struct SwiftUIView: View {
  @ObservedObject var viewModel: MyViewModel
  var body: some View {
    Text(viewModel.foo?.title ?? "")
  }
}
Related