RxSwift update several Variable(s) from one Observable

时间:2017-10-12 10:22:36

标签: swift struct observable rx-swift frp

Structure with several Variables updated from View and from other class

struct MyViewViewModel  {
    let style: Variable<CustomEnum> = Variable(.value1)
    let displayedValue: Variable<String> = Variable("")
    let stepIndex = Variable(0)
    let startedDate: Date

    var disposeBag = DisposeBag()
}

style - updated from 3rt part class

stepIndex - should update from CocoaAction from View and depends from style changing (reseting)

displayedValue - depends from style + stepIndex + startedDate

init(style: Observable<CustomEnum>, startedDate: Date) {
    self.startedDate = startedDate

    style
        .bind(to: self.style)
        .disposed(by: disposeBag)

    self.style.asObservable()
        .map { _ in return 0 }
        .bind(to: stepIndex)
        .disposed(by: disposeBag)

    self.style.asObservable()
        .map { return self.string(for: $0) } //error: Closure cannot implicitly capture a mutating self parameter
        .bind(to: displayedValue)
        .disposed(by: disposeBag)
}


mutating func string(for type: CustomEnum) -> String {
    return "\(self.stepIndex.value) + \(type) + \(self.startedDate.day)"
}

The main question how to process stepIndex variable firstly and after update startedDate value.

I don't want to use class instead structure I am not sure that it is so needed (to avoid retain-cycles). RxSwift should have a way to do without this.

1 个答案:

答案 0 :(得分:0)

简短的回答是你不能。日期需要在初始时设置,但步骤索引流在异步激活中发出值...

让我看到它的唯一方法就是让startDate成为一个var日期?。