Reputation: 315
let manager = CentralManager(queue: .main)
manager.observeStateWithInitialValue()
.filter {$0 == .poweredOn}
.flatMap { _ in manager.scanForPeripherals(withServices: [CBUUID.myDevice.mainService])}
.filter { $0.peripheral.identifier == someSavedIdentifier}
.flatMap { $0.peripheral.establishConnection() }
.flatMap { $0.discoverServices([CBUUID.myDevice.mainService]) }
.flatMap { Observable.from($0) }
.flatMap { $0.discoverCharacteristics([CBUUID.myDevice.businessSecret]) }
.flatMap { Observable.from($0) }
.flatMap { $0.observeValueUpdateAndSetNotification() }
.distinctUntilChanged({ (old, new) -> Bool in
if let oldValue = old.value?.toInt(),
let newValue = new.value?.toInt() {
print("old: \(oldValue), new: \(newValue)")
}
return old.value?.toInt() == new.value?.toInt()
})
.takeUntil(viewDidDisappear)
.subscribe(onNext: { businessSecretValue in
// business logic...
})
.disposed(by: disposeBag)
the distinctUntilChanged works on an Observable (which is a Bluetooth characteristic). I’m trying to have the sequence only contain the characteristics that have a distinct value. But it seems to somehow skip the comparison when they are not equal.
Output sample:
old: 24, new: 24
old: 24, new: 24
old: 24, new: 24
old: 24, new: 24
old: 29, new: 29
old: 29, new: 29
old: 29, new: 29
This is causing it to never find distinct elements. Why isn’t there a line that says:
old: 24, new: 29
Upvotes: 1
Views: 749
Reputation: 33967
I see that
I see that observeValueUpdateAndSetNotification()
returns an Observable<Characteristic>
and that Characteristic
is a class. My guess is that value?.toInt()
is getting changed by something under the hood.
I also see that it is Equatable. Which leads me to wonder why you are even breaking it down in the first place. You should be able to simply do .distinctUntilChanged()
instead of providing a closure.
Old answer
I think you aren't looking closely enough. Note that this:
Observable.from([24, 24, 29, 29])
.debug("in")
.distinctUntilChanged({ (old, new) -> Bool in
print("old:", old, " - new:", new)
return old == new
})
.debug("out")
.subscribe()
Produces this output:
2020-10-20 20:35:00.056: out -> subscribed
2020-10-20 20:35:00.057: in -> subscribed
2020-10-20 20:35:00.058: in -> Event next(24)
2020-10-20 20:35:00.058: out -> Event next(24)
2020-10-20 20:35:00.058: in -> Event next(24)
old: 24 - new: 24
2020-10-20 20:35:00.058: in -> Event next(29)
old: 24 - new: 29 <-- There it is
2020-10-20 20:35:00.058: out -> Event next(29)
2020-10-20 20:35:00.058: in -> Event next(29)
old: 29 - new: 29
2020-10-20 20:35:00.058: in -> Event completed
2020-10-20 20:35:00.058: out -> Event completed
2020-10-20 20:35:00.058: out -> isDisposed
2020-10-20 20:35:00.058: in -> isDisposed
Upvotes: -1