Usage of MVVM in iOS

后端 未结 3 1793
清酒与你
清酒与你 2021-01-30 07:25

I\'m an iOS developer and I\'m guilty of having Massive View Controllers in my projects so I\'ve been searching for a better way to structure my projects and came across the MVV

3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 07:42

    MVVM architecture in iOS can be easily implemented without using third party dependencies. For data binding, we can use a simple combination of Closure and didSet to avoid third-party dependencies.

    public final class Observable {
    
        private var closure: ((Value) -> ())?
    
        public var value: Value {
            didSet { closure?(value) }
        }
    
        public init(_ value: Value) {
            self.value = value
        }
    
        public func observe(_ closure: @escaping (Value) -> Void) {
            self.closure = closure
            closure(value)
        }
    }
    

    An example of data binding from ViewController:

    final class ExampleViewController: UIViewController {
    
        private func bind(to viewModel: ViewModel) {
            viewModel.items.observe(on: self) { [weak self] items in
                self?.tableViewController?.items = items
                // self?.tableViewController?.items = viewModel.items.value // This would be Momory leak. You can access viewModel only with self?.viewModel
            }
            // Or in one line:
            viewModel.items.observe(on: self) { [weak self] in self?.tableViewController?.items = $0 }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            bind(to: viewModel)
            viewModel.viewDidLoad()
        }
    }
    
    protocol ViewModelInput {
        func viewDidLoad()
    }
    
    protocol ViewModelOutput {
        var items: Observable<[ItemViewModel]> { get }
    }
    
    protocol ViewModel: ViewModelInput, ViewModelOutput {}
    final class DefaultViewModel: ViewModel {  
      let items: Observable<[ItemViewModel]> = Observable([])
    
      // Implmentation details...
    }
    

    Later it can be replaced with SwiftUI and Combine (when a minimum iOS version in of your app is 13)

    In this article, there is a more detailed description of MVVM https://tech.olx.com/clean-architecture-and-mvvm-on-ios-c9d167d9f5b3

提交回复
热议问题