ReactiveSwift icon indicating copy to clipboard operation
ReactiveSwift copied to clipboard

Usage with SwiftUI

Open learnwithgabbar opened this issue 3 years ago • 4 comments

learnwithgabbar avatar May 04 '22 08:05 learnwithgabbar

Can you describe your issue? ReactiveSwift works fine with SwiftUI, although you will need to use Combine to bridge state changes to an ObservableObject which is what SwiftUI uses for observing state changes and updating the View.

mluisbrown avatar May 04 '22 08:05 mluisbrown

I want to map property with @Published, any example will help a lot

learnwithgabbar avatar May 04 '22 15:05 learnwithgabbar

Can you describe your issue? ReactiveSwift works fine with SwiftUI, although you will need to use Combine to bridge state changes to an ObservableObject which is what SwiftUI uses for observing state changes and updating the View.

How

learnwithgabbar avatar May 04 '22 15:05 learnwithgabbar

You will need to create an ObservableObject wrapper around the Propertys in your model and when they change, call the send method on the ObservableObjectPublisher.

For example, something like this:

import Combine
import SwiftUI
import ReactiveSwift

class ViewModel: ObservableObject {
  public private(set) lazy var objectWillChange = ObservableObjectPublisher()
  public let count = MutableProperty(0)

  init() {
    count.producer.startWithValues { [weak self] _ in
      self?.objectWillChange.send()
    }
  }
}


struct CounterView: View {
  @ObservedObject var viewModel: ViewModel

  init(viewModel: ViewModel) {
    self.viewModel = viewModel
  }

  var body: some View {
    Text("Count is \(viewModel.count.value)")
  }
}

There is no direct way to map Property to ObservableObject or Published.

mluisbrown avatar Jun 21 '22 20:06 mluisbrown