如何在MVVM中将PublishSubject呈现为Observable?

时间:2018-06-15 13:48:06

标签: swift mvvm protocols rx-swift

我有这样的事情:

for p, vl in pools.items(): 
    alloc = ('{}G'.format(round(sum([float(j[1].split('G')[0]) for j in vl]))))
    free = ('{}G'.format(round(sum([float(j[2].split('G')[0]) for j in vl]))))


I need to add values accordingly: 
from key1 aaaaa value 834M + 
from key1 bbbbb value 216G
then 
from key1 aaaaa value 118G +
from key1 bbbbb value 220.3M 
and so on for every key
so the output will look like this:

 216.8G 118.2G

我想与protocol ViewModel: class { var eventWithInitialValue: Observable<Int> { get } } class ViewModelImpl: ViewModel { let eventWithInitialValue: BehaviorSubject<Int> = BehaviorSubject(value: 0) init() { eventWithInitialValue.onNext(1) } } class ViewController: UIViewController { weak var viewModel: ViewModel? private let bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() viewModel? .eventWithInitialValue .subscribe(onNext: { print($0) }).disposed(by: bag) } } 中的viewModel字段作为ViewController进行通信。但在Observables内,此字段应为viewModel类型(出于安全原因)。

上面的实现有下一个编译时错误 - &gt; [OneOf]Subject

任何人都可以帮助实施这些要求吗?

2 个答案:

答案 0 :(得分:0)

你的问题不在于Rx,你的错误与你的协议有关

这将解决当前的问题

protocol ViewModel: class {
    var eventWithInitialValue: BehaviorSubject<Int> { get }
}

class ViewModelImpl: ViewModel {

    var eventWithInitialValue: BehaviorSubject<Int> = BehaviorSubject(value: 0)

    init() {
        eventWithInitialValue.onNext(1)
    }
}

答案 1 :(得分:0)

我认为您有这个Type 'ViewModelImpl' does not conform to protocol 'ViewModel'是因为您在实现中将eventWithInitialValue的类型定义为BehaviorSubject。 我可以建议的就是这样

protocol ViewModel {
    var data: Observable<Int> { get}
}

class ViewModelImpl: ViewModel {
    private let dataSubject = BehaviorSubject(value: 1)
    var data: Observable<Int> {
        return dataSubject
    }
}