I have a ViewModel where an service class is defined, This service class is initialized in this ViewModel's initializer. Now I need to update my View when there is any change in its value in ViewModel(getting it from service). Although I have found some examples of using Variable but I could not find it with Class injection. 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
Following is how the ViewModel initialized:
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:
self.presenter = CardViewModel(service: CardService())
Edit2:
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
But keep in mind that RxSwift 4.0.0 "Deprecates Variable in favor of BehaviorRelay."
If you are not obliged to follow MVVM, you can try unidirectional dataflow approach instead - https://github.com/maxvol/RaspSwift
In case to have a continuous subscription to server updates, you can use .switchLatest() operator like that -
let stream = PublishSubject<Observable<Response>>()
stream.switchLatest().subscribe(consumer)
stream.onNext(serverRequestReturningResponseObservable) // repeat whenever needed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.