Skip to content

4. Connecting to peripheral

paweljaneczek edited this page Sep 11, 2018 · 2 revisions

In order to establishConnection between device and peripheral, you will need to:

// scannedPeripheral is a peripheral received from scanForPeripherals method
let scannedPeripheral: ScannedPeripheral = ... 
let disposable = scannedPeripheral.peripheral.establishConnection()
    .subscribe(onNext: { print("Connected to: \($0)") })

and to close that connection you simply need to:

disposable.dispose()

Easy, right? Here is a example with scanning observable chain:

manager.scanForPeripherals(withServices: [serviceId]).take(1)
    .flatMap { $0.peripheral.establishConnection() }
    .subscribe(onNext: { peripheral in
        print("Connected to: \(peripheral)")
    })

The best part is here - check out how it can be compound with observing state:

manager.observeState()
     .startWith(state)
     .filter { $0 == .poweredOn }
     .flatMap { manager.scanForPeripherals(withService: [serviceId]) }
     .take(1)
     .flatMap { $0.peripheral.establishConnection() }
     .subscribe(onNext: { peripheral in
          print("Connected to: \(peripheral)")
     })

With just 8 lines of code it:

  • waited for .poweredOn state
  • started scanning after it receives it
  • connected to first scanned peripheral