0

I use some BehaviourRelay for some variable. And I use withLatestFrom for one of them. But withLatestFrom didn't return the latest value I bind to it.

If I use combineLatest. It works but I want to know why the code with withLatestFrom not work

let dueDate = BehaviorRelay<Date?>(value: nil)
let numberScheduleDays = BehaviorRelay<Int>(value: 1)
let selectedPaymentDate = BehaviorRelay<Date?>(value: nil)

dueDate.asObservable()
    .distinctUntilChanged()
    .flatMap { Observable.from(optional: $0) }
    .map { self.addDaysForDate(days: 1, date: $0) }
    .bind(to: selectedPaymentDate)
    .disposed(by: disposeBag)

selectedPaymentDate.asObservable()
    .distinctUntilChanged()
    .withLatestFrom(dueDate.asObservable()) { (selectedDate: $0, dueDate: $1) }
    .map { self.daysBetweenDates(startDate: $0.dueDate, endDate: $0.selectedDate) }
    .bind(to: numberScheduleDays)
    .disposed(by: disposeBag)

dueDate.accept(Date())

After block one selectedPaymentDate.value = Date() + 1 But in block two dueDate still emit nil value. I wonder why its value is not Date()

Mukesh
  • 2,792
  • 15
  • 32
Hoangtaiki
  • 41
  • 3
  • 5

1 Answers1

1

withLatestFrom assumes that two observable sequence have different source and they don't fire simultaneously (Like in your case they have same source).

If two observable sequences fire simultaneously then they can be solved by using single sequence.

For more info read:

withLatestFrom doesn't actually provide latest value

Mukesh
  • 2,792
  • 15
  • 32