How to connect published properties of model and viewmodel in Swift? - swift

Let's assume a model, which implements the protocol ObservableObject and has got a #Published property name.
// MARK: Model
class ContentSinglePropertyModel: ObservableObject {
#Published public var name: String
}
Now, I would like to display that name in a view and update the view, whenever name in the model changes. Additionally, I would like to use the Model-View-ViewModel (MVVM) pattern to achieve this goal.
// MARK: ViewModel
final class ContentSinglePropertyViewModel: ObservableObject {
private let model: ContentSinglePropertyModel
#Published var name: String = ""
init() {
self.model = ContentSinglePropertyModel()
}
}
// MARK: View
struct ContentSinglePropertyView: View {
#ObservedObject var viewModel: ContentSinglePropertyViewModel
var body: some View {
Text(self.viewModel.name)
}
}
Since I don't like the idea to make the model or it's properties public within the viewmodel, one option is to wrap the model's property name in the viewmodel. My question is: How to connect the name of the model and the viewmodel in the most idiomatic way?
I've came up with the solution to update the viewmodel's property through the use of Combine's assign method:
self.model.$name.assign(to: \.name, on: self).store(in: &self.cancellables)
Is there a better solution?
My working example:
import SwiftUI
import Combine
// MARK: Model
class ContentSinglePropertyModel: ObservableObject {
#Published public var name: String
init() {
self.name = "Initial value"
}
func doSomething() {
self.name = "Changed value"
}
}
// MARK: ViewModel
final class ContentSinglePropertyViewModel: ObservableObject {
private let model: ContentSinglePropertyModel
private var cancellables: Set<AnyCancellable> = []
#Published var name: String = ""
init() {
self.model = ContentSinglePropertyModel()
// glue Model and ViewModel
self.model.$name.assign(to: \.name, on: self).store(in: &self.cancellables)
}
func doSomething() {
self.model.doSomething()
}
}
// MARK: View
struct ContentSinglePropertyView: View {
#ObservedObject var viewModel: ContentSinglePropertyViewModel
var body: some View {
VStack {
Text(self.viewModel.name)
Button("Do something!", action: {
self.viewModel.doSomething()
})
}
}
}
struct ContentSinglePropertyView_Previews: PreviewProvider {
static var previews: some View {
ContentSinglePropertyView(viewModel: .init())
}
}

Related

Using Sub Interactor for an Interactor in SwiftUI - Failed to produce diagnostic for expression

I have created a simple SubInteractor with #Published var and then there is a MainInteractor using that SubInteractor and a MainView that has access to MainInteractor.
That MainView needs to pass the #Published var down to a subview by accessing it through the MainInteractor.
Using the following code to create a SubInteractor inside MainInteractor gives an error:
Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project
import Foundation
import Combine
import SwiftUI
protocol SubInteractorProtocol {
var name: String { get set }
}
class SubInteractor: ObservableObject & SubInteractorProtocol {
#Published var name: String = "name"
}
protocol MainInteractorProtocol {
associatedtype SubType: ObservableObject & SubInteractorProtocol
var subInteractor: SubType { get set }
}
class MainInteractor: ObservableObject & MainInteractorProtocol {
#ObservedObject var subInteractor: SubInteractor
init(subInteractor: SubInteractor) {
self.subInteractor = subInteractor
}
}
struct NameView: View {
#Binding var name: String
var body: some View {
Text("\(name)")
}
}
struct MainView<Interactor: ObservableObject & MainInteractorProtocol>: View {
#EnvironmentObject var c: Interactor
var body: some View {
NameView(name: $c.subInteractor.name)
}
}
I also tried changing the SubInteractorProtocol and SubInteractor to this (but get the same error):
protocol SubInteractorProtocol {
var name: String { get set }
var namePublished: Published<String> { get }
var namePublisher: Published<String>.Publisher { get }
}
class SubInteractor: ObservableObject & SubInteractorProtocol {
#Published var name = "name"
var namePublished: Published<String> { _name }
var namePublisher: Published<String>.Publisher { $name }
}
Any suggestions about how to accomplish this?
I found a way to solve this, I use subInteractor and there is no need to use #Published or #ObservedObject on the SubInteractor. I pass the SubInteractor down to the view that needs it instead of passing a published variable owned by SubInteractor.
import Foundation
import Combine
import SwiftUI
class SubInteractor: ObservableObject {
#Published var count = 1
init() {
}
}
protocol MainInteractorProtocol: ObservableObject {
var subInteractor: SubInteractor { get set }
}
class MainInteractor: ObservableObject & MainInteractorProtocol {
var subInteractor: SubInteractor
init(subInteractor: SubInteractor) {
self.subInteractor = subInteractor
}
}
struct NameView: View {
#ObservedObject var s: SubInteractor
var body: some View {
Text("\(s.count)")
}
}
And to call it:
struct MainView<Interactor: ObservableObject & MainInteractorProtocol>: View {
#EnvironmentObject var c: Interactor
var body: some View {
VStack {
Button(action: {
c.subInteractor.count += 1
}, label: {
Text("increment")
})
NameView(s: c.subInteractor)
}
}
}

How to observer a property in swift ui

How to observe property value in SwiftUI.
I know some basic publisher and observer patterns. But here is a scenario i am not able to implement.
class ScanedDevice: NSObject, Identifiable {
//some variables
var currentStatusText: String = "Pending"
}
here CurrentStatusText is changed by some other callback method that update the status.
Here there is Model class i am using
class SampleModel: ObservableObject{
#Published var devicesToUpdated : [ScanedDevice] = []
}
swiftui component:
struct ReviewView: View {
#ObservedObject var model: SampleModel
var body: some View {
ForEach(model.devicesToUpdated){ device in
Text(device.currentStatusText)
}
}
}
Here in UI I want to see the real-time status
I tried using publisher inside ScanDevice class but sure can to use it in 2 layer
You can observe your class ScanedDevice, however you need to manually use a objectWillChange.send(),
to action the observable change, as shown in this example code.
class ScanedDevice: NSObject, Identifiable {
var name: String = "some name"
var currentStatusText: String = "Pending"
init(name: String) {
self.name = name
}
}
class SampleViewModel: ObservableObject{
#Published var devicesToUpdated: [ScanedDevice] = []
}
struct ReviewView: View {
#ObservedObject var viewmodel: SampleViewModel
var body: some View {
VStack (spacing: 33) {
ForEach(viewmodel.devicesToUpdated){ device in
HStack {
Text(device.name)
Text(device.currentStatusText).foregroundColor(.red)
}
Button("Change \(device.name)") {
viewmodel.objectWillChange.send() // <--- here
device.currentStatusText = UUID().uuidString
}.buttonStyle(.bordered)
}
}
}
}
struct ContentView: View {
#StateObject var viewmodel = SampleViewModel()
var body: some View {
ReviewView(viewmodel: viewmodel)
.onAppear {
viewmodel.devicesToUpdated = [ScanedDevice(name: "device-1"), ScanedDevice(name: "device-2")]
}
}
}

How to trigger automatic SwiftUI Updates with #ObservedObject using MVVM

I have a question regarding the combination of SwiftUI and MVVM.
Before we start, I have read some posts discussing whether the combination of SwiftUI and MVVM is necessary. But I don't want to discuss this here, as it has been covered elsewhere. I just want to know if it is possible and, if yes, how. :)
So here comes the code. I tried to add the ViewModel Layer in between the updated Object class that contains a number that should be updated when a button is pressed. The problem is that as soon as I put the ViewModel Layer in between, the UI does not automatically update when the button is pressed.
View:
struct ContentView: View {
#ObservedObject var viewModel = ViewModel()
#ObservedObject var numberStorage = NumberStorage()
var body: some View {
VStack {
// Text("\(viewModel.getNumberObject().number)")
// .padding()
// Button("IncreaseNumber") {
// viewModel.increaseNumber()
// }
Text("\(numberStorage.getNumberObject().number)")
.padding()
Button("IncreaseNumber") {
numberStorage.increaseNumber()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
ViewModel:
class ViewModel: ObservableObject {
#Published var number: NumberStorage
init() {
self.number = NumberStorage()
}
func increaseNumber() {
self.number.increaseNumber()
}
func getNumberObject() -> NumberObject {
self.number.getNumberObject()
}
}
Model:
class NumberStorage:ObservableObject {
#Published var numberObject: NumberObject
init() {
numberObject = NumberObject()
}
public func getNumberObject() -> NumberObject {
return self.numberObject
}
public func increaseNumber() {
self.numberObject.number+=1
}
}
struct NumberObject: Identifiable {
let id = UUID()
var number = 0
} ```
Looking forward to your feedback!
I think your code is breaking MVVM, as you're exposing to the view a storage model. In MVVM, your ViewModel should hold only two things:
Values that your view should display. These values should be automatically updated using a binding system (in your case, Combine)
Events that the view may produce (in your case, a button tap)
Having that in mind, your ViewModel should wrap, adapt and encapsulate your model. We don't want model changes to affect the view. This is a clean approach that does that:
View:
struct ContentView: View {
#StateObject // When the view creates the object, it must be a state object, or else it'll be recreated every time the view is recreated
private var viewModel = ViewModel()
var body: some View {
VStack {
Text("\(viewModel.currentNumber)") // We don't want to use functions here, as that will create a new object , as SwiftUI needs the same reference in order to keep track of changes
.padding()
Button("IncreaseNumber") {
viewModel.increaseNumber()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
ViewModel:
class ViewModel: ObservableObject {
#Published
private(set) var currentNumber: Int = 0 // Private set indicates this should only be mutated by the viewmodel
private let numberStorage = NumberStorage()
init() {
numberStorage.currentNumber
.map { $0.number }
.assign(to: &$currentNumber) // Here we're binding the current number on the storage to the published var that the view is listening to.`&$` basically assigns it to the publishers address
}
func increaseNumber() {
self.numberStorage.increaseNumber()
}
}
Model:
class NumberStorage {
private let currentNumberSubject = CurrentValueSubject<NumberObject, Never>(NumberObject())
var currentNumber: AnyPublisher<NumberObject, Never> {
currentNumberSubject.eraseToAnyPublisher()
}
func increaseNumber() {
let currentNumber = currentNumberSubject.value.number
currentNumberSubject.send(.init(number: currentNumber + 1))
}
}
struct NumberObject: Identifiable { // I'd not use this, just send and int directly
let id = UUID()
var number = 0
}
It's a known problem. Nested observable objects are not supported yet in SwiftUI. I don't think you need ViewModel+Model here since ViewModel seems to be enough.
To make this work you have to trigger objectWillChange of your viewModel manually when objectWillChange of your model is triggered:
class ViewModel: ObservableObject {
init() {
number.objectWillChange.sink { [weak self] (_) in
self?.objectWillChange.send()
}.store(in: &cancellables)
}
}
You better listen to only the object you care not the whole observable class if it is not needed.
Plus:
Since instead of injecting, you initialize your viewModel in your view, you better use StateObject instead of ObservedObject. See the reference from Apple docs: Managing model data in your app
One way you could handle this is to observe the publishers in your Storage class and send the objectWillChange publisher when it changes. I have done this in personal projects by adding a class that all my view models inherit from which provides a nice interface and handles the Combine stuff like this:
Parent ViewModel
import Combine
class ViewModel: ObservableObject {
private var cancellables: Set<AnyCancellable> = []
func publish<T>(on publisher: Published<T>.Publisher) {
publisher.sink { [weak self] _ in self?.objectWillChange.send() }
.store(in: &cancellables)
}
}
Specific ViewModel
class ContentViewModel: ViewModel {
private let numberStorage = NumberStorage()
var number: Int { numberStorage.numberObject.number }
override init() {
super.init()
publish(on: numberStorage.$numberObject)
}
func increaseNumber() {
numberStorage.increaseNumber()
}
}
View
struct ContentView: View {
#StateObject var viewModel = ContentViewModel()
var body: some View {
VStack {
Text("\(viewModel.number)")
.padding()
Button("IncreaseNumber") {
viewModel.increaseNumber()
}
}
}
}
Model/Storage
class NumberStorage:ObservableObject {
#Published var numberObject: NumberObject
init() {
numberObject = NumberObject()
}
public func increaseNumber() {
self.numberObject.number += 1
}
}
struct NumberObject: Identifiable {
let id = UUID()
var number = 0
}
This results in the view re-rendering any time Storage.numberObject changes.

Xcode will not let me use `#ObservedObject` on an optional

I have a ObservableObject class called MyObjectModel that is passed to a struct like this:
var body: some View {
MyView(myObjectModel)
But on another context I do not have a model to pass, so I want to call MyView simply as
var body: some View {
MyView()
So I thought I could initialize MyView like
struct MyView: View {
#ObservedObject private var model: MyObjectModel?
init(model: MyObjectModel? = nil) {
self.model = model
}
But Xcode will not let me use #ObservedObject on an optional.
How do I do that?
The ObservedObject wrapper does not have constructor with optional for now (and we cannot extend Optional with conformance to ObservableObject, because it is not a class).
A possible approach is to have some specific mark that there is no model, as it would be nil.
Here is a demo:
class MyObjectModel: ObservableObject {
static let None = MyObjectModel() // Like NSNull.null
}
struct MyView: View {
#ObservedObject private var model: MyObjectModel
init(model: MyObjectModel? = nil) {
self.model = model ?? MyObjectModel.None
}
var body: some View {
if self.model === MyObjectModel.None {
Text("Same as it would be nil!") // << here !!
} else {
Text("For real model")
}
}
}

How to pass a Publisher to a class

I have a model class which holders a few publishers as the source of truth. And I also have a few classes that processes data. I need to process data depending on a publisher from the model class.
class Model: ObservableObject {
#Published var records = [Record]()
let recordProcessor: RecordProcessor
init() {
...
}
}
class RecordProcessor: ObservableObject {
#Published var results = [Result]()
}
struct RootView: View {
var body: some View {
MyView()
.environmentObject(Model())
}
}
struct MyView: View {
#EnvironmentObject var model: Model
var body: some View {
ForEach(model.recordProcessor.results) { ... }
}
}
RecordProcessor does a lot of work on records so the work is encapsulated into a class, but the input is the records stored on the Model. What is a proper way of passing in the records to the RecordProcessor?
Assuming Record is a value type, here is possible way (as far as I understood your goal)
class Model: ObservableObject {
#Published var records = [Record]() {
didSet {
recordProcessor.process(records) // << something like this
}
}
let recordProcessor: RecordProcessor
init(processor: RecordProcessor) {
self.recordProcessor = processor
}
}
class RecordProcessor: ObservableObject {
#Published var results = [Result]()
func process(_ records: [Record]) {
}
}
The best I'm come up with is to have the RecordProcessor process the data and return a publisher with the results:
struct Record {}
struct Result {}
class Model: ObservableObject {
#Published var records = [Record]()
#Published var results = [Result]()
let recordProcessor = RecordProcessor()
var cancellables = Set<AnyCancellable>()
init() {
$records
.map(recordProcessor.process)
.switchToLatest()
.sink {
self.results = $0
}
.store(in: &cancellables)
}
}
class RecordProcessor: ObservableObject {
func process(items: [Record]) -> AnyPublisher<[Result], Never> {
return Just([]).eraseToAnyPublisher()
}
}
struct RootView: View {
var body: some View {
MyView()
.environmentObject(Model())
}
}
struct MyView: View {
#EnvironmentObject var model: Model
var body: some View {
ForEach(model.results) { }
}
}