6. Reading & Writing to characteristic value

paweljaneczek edited this page Jul 2, 2018 · 2 revisions


Once you've got characteristic, next common step is to read value from it. In order to do that, you should use readValue() function defined on Characteristic. It returns Observable<Characteristic> which emits element, when value of characteristic is ready to read. We decided to return Characteristic instead of NSData due to one purpose - to allow you chain operations on characteristic in easy way.

    .flatMap { $0.discoverServices([serviceId]) }.asObservable()
    .flatMap { Observable.from($0) }
    .flatMap { $0.discoverCharacteristics([characteristicId])}.asObservable()
    .flatMap { Observable.from($0) }
    .flatMap { $0.readValue() }
    .subscribe(onNext: {
        let data = $0.value


While deciding to write to characteristic you have two writing options, that determine write behavior:

  • .withResponse
  • .withoutResponse

Choosing .withResponse, you're waiting to receive .next event on Observable while device has confirmed that value has been written to it. Also, if any error has occurred - you will receive .error on Observable. On the other hand - if you decided to go with .withoutResponse - you'd receive Characteristic just after write command has been called. Also, no errors will be emitted.

Let's jump over to the code:

characteristic.writeValue(data, type: .withResponse)
    .subscribe { event in
        //respond to errors / successful read
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.