94 lines
2.5 KiB
Swift
94 lines
2.5 KiB
Swift
//
|
|
// ModelViewController.swift
|
|
// VDSSample
|
|
//
|
|
// Created by Matt Bruce on 8/15/22.
|
|
//
|
|
|
|
import Foundation
|
|
import UIKit
|
|
import Combine
|
|
import VDS
|
|
|
|
public class ModelViewController<ModelType: Modelable>: UIViewController {
|
|
deinit {
|
|
print("\(Self.self) deinit")
|
|
}
|
|
|
|
//--------------------------------------------------
|
|
// MARK: - Combine Properties
|
|
//--------------------------------------------------
|
|
public var model = CurrentValueSubject<ModelType, Never>(ModelType())
|
|
public var subscribers = Set<AnyCancellable>()
|
|
|
|
//--------------------------------------------------
|
|
// MARK: - Properties
|
|
//--------------------------------------------------
|
|
private var initialSetupPerformed = false
|
|
|
|
@Proxy(\.model.value.surface)
|
|
open var surface: Surface
|
|
|
|
@Proxy(\.model.value.disabled)
|
|
open var disabled: Bool
|
|
|
|
//--------------------------------------------------
|
|
// MARK: - Initializers
|
|
//--------------------------------------------------
|
|
required public init() {
|
|
super.init(nibName: nil, bundle: nil)
|
|
initialSetup()
|
|
}
|
|
|
|
public required init(with model: ModelType) {
|
|
super.init(nibName: nil, bundle: nil)
|
|
initialSetup()
|
|
set(with: model)
|
|
}
|
|
|
|
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
|
|
super.init(nibName: nil, bundle: nil)
|
|
initialSetup()
|
|
}
|
|
|
|
public required init?(coder: NSCoder) {
|
|
super.init(coder: coder)
|
|
initialSetup()
|
|
}
|
|
|
|
//--------------------------------------------------
|
|
// MARK: - Setup
|
|
//--------------------------------------------------
|
|
|
|
public func initialSetup() {
|
|
if !initialSetupPerformed {
|
|
initialSetupPerformed = true
|
|
model
|
|
.filter { [weak self] viewModel in
|
|
return self?.shouldUpdateView(viewModel: viewModel) ?? false
|
|
|
|
}
|
|
.debounce(for: .seconds(Constants.ModelStateDebounce), scheduler: RunLoop.main)
|
|
.sink { [weak self] viewModel in
|
|
self?.updateView()
|
|
|
|
}
|
|
.store(in: &subscribers)
|
|
setup()
|
|
}
|
|
}
|
|
|
|
open func setup() {}
|
|
|
|
open func shouldUpdateView(viewModel: ModelType) -> Bool { true }
|
|
|
|
open func updateView() {}
|
|
|
|
open func set(with model: ModelType) {
|
|
if shouldUpdateView(viewModel: model){
|
|
self.model.send(model)
|
|
}
|
|
}
|
|
|
|
}
|