简体   繁体   English

观察类变量以了解RxSwift中viewModel的任何更改

[英]observing a class Variable for any change in viewModel in RxSwift

I have a ViewModel where an service class is defined, This service class is initialized in this ViewModel's initializer. 我有一个定义服务类的ViewModel,此服务类在此ViewModel的初始化程序中初始化。 Now I need to update my View when there is any change in its value in ViewModel(getting it from service). 现在,当ViewModel中的值发生任何更改(从服务中获取)时,我需要更新View。 Although I have found some examples of using Variable but I could not find it with Class injection. 尽管我找到了一些使用Variable的示例,但是在Class Injection中却找不到。 ViewController: ViewController:

    var presenter:Variable<CardViewModelProtocol>!
        func setPresenter() {
//Following line has error
            self.presenter = Variable<CardViewModelProtocol>(CardViewModelProtocol(service:CardService()))
            self.presenter.value.attachView(view: self)
        }

the line where presenter is initialized is giving error. 演示者初始化的行给出了错误。 Error: 错误:

'CardPresenterProtocol' cannot be constructed because it has no accessible initializers 无法构造“ CardPresenterProtocol”,因为它没有可访问的初始化程序

Following is how the ViewModel initialized: 以下是ViewModel的初始化方式:

var cardService:CardServiceContract!
var materialNum = Variable<String>("")

init(service:CardServiceContract){
    self.cardService = service
}

Edit1: In short I want to convert following line to RxSwift supporting Variables and observe a variable(class object) in CardViewModel: Edit1:简而言之,我想将以下行转换为支持变量的RxSwift并在CardViewModel中观察一个变量(类对象):

self.presenter = CardViewModel(service: CardService())

Edit2: 编辑2:

    protocol CardViewModelProtocol : BaseViewModelProtocol {

    func loadCardInfo(Serial serial:String)

    var materialNum: Variable<String> {get set}
}
protocol BaseViewModelProtocol {
    func attachView(view: BaseViewProtocol)
}
protocol BaseViewProtocol{
    func setViewModel()
}

This is an example of usage - https://github.com/RxSwiftCommunity/RxSegue/blob/master/Example/RxSegue/ProfileViewController.swift 这是用法的一个示例-https: //github.com/RxSwiftCommunity/RxSegue/blob/master/Example/RxSegue/ProfileViewController.swift

But keep in mind that RxSwift 4.0.0 "Deprecates Variable in favor of BehaviorRelay." 但是请记住,RxSwift 4.0.0“赞成使用BehaviorRelay弃用变量”。

If you are not obliged to follow MVVM, you can try unidirectional dataflow approach instead - https://github.com/maxvol/RaspSwift 如果您没有义务遵循MVVM,则可以尝试单向数据流方法-https: //github.com/maxvol/RaspSwift

In case to have a continuous subscription to server updates, you can use .switchLatest() operator like that - 如果要连续订阅服务器更新,可以使用.switchLatest()运算符,例如:

let stream = PublishSubject<Observable<Response>>()
stream.switchLatest().subscribe(consumer)
stream.onNext(serverRequestReturningResponseObservable) // repeat whenever needed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM