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?"
2
Answers
The easiest one is by using Observable class binding known as Boxing.
create an Observable class:
in your viewModel define it in this way:
(this is a sample for showing loader in your view controller)
Because the Observable class is a generic type, you can pass other types to it.
in your view model you can set the value:
then in your view controller use something like this:
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.
Due to I need multiple observer and I don’t want the closure still exist when the ViewController is gone.
I make some changes from Sajjad Sarkoobi code.
in your viewModel define it in this way
Set the value in ViewModel
Use bind and unbind in your ViewController. I want the closure removed from Observable listeners array, so I unbind it when viewController deinit.