ReactiveSwift 简单使用

记录 ReactiveSwift 简单使用

  1. 导入 ReactiveSwift 库
  2. 创建 TestViewModel 文件
c 复制代码
enum JKTypeType: Int {
    case cloud
    case device
    case weater
}

// 通过监听属性变化
class TestViewModel: NSObject {
    
    lazy var recordType: Property<JKTypeType> = {
        return Property(recordTypeProperty)
    }()
    
    private(set) var recordTypeProperty: MutableProperty<JKTypeType> = MutableProperty(.device)

    deinit {
        print("TestViewModel delloc")
    }
}

extension TestViewModel {
    
    func setRecordType(_ type: JKTypeType) {
        recordTypeProperty.value = type
    }
    
}
  1. 使用 TestViewModel
c 复制代码
class RegisterVC: UIViewController {
	var testViewModel =  TestViewModel()
    
    let disposes: CompositeDisposable = CompositeDisposable()

	override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        bindViewModel()
    }

	func bindViewModel() {
         disposes += testViewModel.recordType.signal.observeValues { type in
            print("testViewModel: \(type)")
        }
    }


	@IBAction func backClick(_ sender: Any) {
        testViewModel.setRecordType(.cloud)
     }
}

	deinit {
        disposes.dispose()
    }
相关推荐
大熊猫侯佩7 小时前
iOS 18 中全新 SwiftData 重装升级,其中一个功能保证你们“爱不释手”
数据库·ios·swift
YungFan1 天前
SwiftUI-自定义与扩展
swiftui·swift
东坡肘子1 天前
WWDC 2025 开发者特辑 | 肘子的 Swift 周报 #088
swiftui·swift·wwdc
大熊猫侯佩1 天前
Swift 中强大的 Key Paths(键路径)机制趣谈(下)
swift·编程语言·apple
season_zhu1 天前
RxSwift:dispose() 和 disposed(by:) 以及NSObject+Rx
ios·swift·rxswift
健了个平_242 天前
iOS 26 适配笔记
ios·swift·wwdc
大熊猫侯佩2 天前
Swift 协议扩展精进之路:解决 CoreData 托管实体子类的类型不匹配问题(上)
swift·协议·protocol·coredata·协议扩展·托管基类·协议关联类型