I am working with MVVM design architecture, I have gone through multiple articles about data binding. We can achieve data binding through Protocol, Closure, and Third Party(like RxSwift). So, if I am wrong please correct me otherwise let me know "how many ways to bind the data in iOS(Swift) MVVM design architecture?"
CodePudding user response:
Beside what you mentioned you can also use Combine framework and "Boxing" - observable objects
CodePudding user response:
The easiest one is by using Observable class binding known as Boxing. create an Observable class:
class Observable<T> {
var value: T? {
didSet {
DispatchQueue.main.async {
self.listener?(self.value)
}
}
}
init( _ value: T?) {
self.value = value
}
private var listener: ((T?) -> Void)?
func bind(_ listener: @escaping (T?) -> Void) {
listener(value)
self.listener = listener
}
}
in your viewModel define it in this way: (this is a sample for showing loader in your view controller)
var isLoadingData: Observable<Bool> = Observable(false)
Because the Observable class is a generic type, you can pass other types to it.
in your view model you can set the value:
isLoadingData.value = true
then in your view controller use something like this:
viewModel.isLoadingData.bind { [weak self] loading in
guard let loading = loading, let self = self else {
return
}
DispatchQueue.main.async {
if loading {
//Show a loader
} else {
//Hide a loader
}
}
}
As soon as a value is assigned to the isLoadingData object, it will trigger your view controller. We have to use [Weak self] to avoid strong references.