首页 > 解决方案 > Swift 中的简单期货模式

问题描述

我是期货新手,我不明白如何拆分现有代码操作,因为我没有任何好的示例来理解期货,我正在使用 BlueCapKit BLE 库,该库在后台使用 Simple Futures iOS 库和以下示例客户端代码:

    let stateChangeFuture = manager.whenStateChanges()
    
    /// Handles state changes and returns a scan future if the bluetooth is powered on
    let scanFuture = stateChangeFuture.flatMap { state -> FutureStream<Peripheral> in
        switch state {
        case .poweredOn:
            /// Scans for peripherals which have our service
            return manager.startScanning(forServiceUUIDs: [self.serviceUUID])
        //...
        }
    }
    scanFuture.onFailure { error in
        // ...
    }

let connectionFuture = scanFuture.flatMap { p -> FutureStream<Void> in
            /// Stops the scan when we find the first peripheral
            manager.stopScanning()
            // store some advertising data, cache the peripheral
            return p.connect(connectionTimeout: TimeInterval.infinity, capacity: Int.max)
        }

let discoveryFuture = connectionFuture.flatMap { _ -> Future<Void> in
   // triggered after connection
}

我想知道如何将设备列表操作(即在连接调用之前)从连接拆分到选定的特定设备。

就像是:

func listDevices() {
   // first we list every devices
   // ...
   let connectionFuture = scanFuture.flatMap { p -> FutureStream<Void> in
        /// Stops the scan when we find the first peripheral
        manager.stopScanning()
        // store some advertising data, cache the peripheral
        return
    }
}


func connectToDevice(int index) {
    // when the user pressed a button, we connect:
     let f = self.cachedPeripherals[index].connect(connectionTimeout: TimeInterval.infinity, 
     capacity: Int.max).flatMap {
      
     }
     let discoveryFuture = f.flatMap { _ -> Future<Void> in
          // triggered after connection
     }
 }

这是好方法吗?我不知道何时触发未来的操作。

标签: swiftfuture

解决方案


推荐阅读