swiftrx-swiftrxandroidblerxbluetooth

Chaining multiple commands in RxBluetoothKit


Previously I had this question regarding the awesome rxAndroidBle - Writing multiple commands to characteristic

The solution works great!

Now the time has come to port this app over to an iOS version and I am struggling to find a suitable way to achieve the same result.

Basically I need to send a series of commands, in sequence to the peripheral, the commands need to send in order and the next command should send when the previous has completed, ideally with a final event when all commands have been sent, just like in the android app snippet in the above link

The below code does the job but as you see it is not pretty and also can easily become unmanageable as the quantity of commands grows!

The android app uses Single.concat, what is the equivalent for RxSwift?

self.writeCharacteristic?.writeValue(command1, type: .withResponse)
        .subscribe {
            print("Command 1 complete ", $0 )
            self.writeCharacteristic?.writeValue(command2, type: .withResponse)
                .subscribe {
                    print("command2 complete ", $0 )

            }
    }

Any pointers greatly appreciated!!! thank you


Solution

  • Single doesn't have concat method, but you can just us Observable.concat and call asObservable() for each writeValue method, like this:

    Observable.concat(
            characteristic.writeValue(command1, type: .withResponse).asObservable(),
            characteristic.writeValue(command2, type: .withResponse).asObservable(),
            characteristic.writeValue(command3, type: .withResponse).asObservable(),
            ...
            characteristic.writeValue(command4, type: .withResponse).asObservable()
            ).subscribe { event in
                switch event {
                case .next(let characteristic):
                    print("Did write for characteristic \(characteristic)")
                case .error(let error):
                    print("Did fail with error \(error)")
                case .completed:
                    print("Did completed")
                }
            }