简体   繁体   中英

Binding BehaviorRelay with Observable - RxSwift

I have such code as below. How can I achieve it in one chain, without using subscribe on timer? I would like to attach 'timerInterval' to 'timer' and then call subscribe.

var timerInterval: BehaviorRelay<String> = BehaviorRelay(value: "")

...

func doLogic() {
    let timer = Observable<Int>.interval(0.05, scheduler: MainScheduler.instance)

    timer.subscribe({ [weak self] value in
            let doubleValue = Double(value.element ?? 0)
            let dividedValue = doubleValue / 20.0
            let text = String(format: "%.2f", dividedValue)
            self?.timerInterval.accept(text)
        }).disposed(by: disposeBag)
}

You'd go for map operator. I'm not sure why you need BehaviourRelay but I'd do something even more simpler:

let timer = Observable<Int>.interval(0.05, scheduler: MainScheduler.instance)

var timerInterval: Observable<String> {
   return timer.map { value -> String in
             let doubleValue = Double(value.element ?? 0)
             let dividedValue = doubleValue / 20.0
             let text = String(format: "%.2f", dividedValue)
             return text
          }
}

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.

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