PromiseKit 4 - 包装委托
Posted
技术标签:
【中文标题】PromiseKit 4 - 包装委托【英文标题】:PromiseKit 4 - Wrap Delegation 【发布时间】:2016-10-11 01:00:44 【问题描述】:我正在尝试使用 Promisekit 实现一个带有包装委托的单例
我设法按照这里的描述实现了这一点: https://github.com/mxcl/PromiseKit/issues/136
它有效,但承诺保留第一次调用的值。它不会更新值。
示例代码:
open class APIClient: NSObject
static let sharedInstance = APIClient()
var mSocket: GCDAsyncSocket!
var deferred = Promise<[String:Any]>.pending()
var retainCycle: NSObject?
override init()
mSocket = GCDAsyncSocket()
super.init()
mSocket.setDelegate(self, delegateQueue: DispatchQueue.main)
deferred.promise.always
print(self) // here we force a retain on self inside the promise object
// it will be released once processed
.catch (error) in
// MARK: - sendMessageTCP
open func sendMessageTCP(message data:Data) -> Promise<[String:Any]>
mSocket.write(data, withTimeout: 10, tag: 0)
return deferred.promise
extension APIClient: GCDAsyncSocketDelegate
public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int)
sock.readData(withTimeout: -1, tag: 0)
public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int)
let array = data.withUnsafeBytes
[UInt8](UnsafeBufferPointer(start: $0, count: data.count))
let parameters: [String:Any] = [
"status": true,
"data": bytesToHexString(bytes: array),
"ui_message": "Read Data"
]
deferred.fulfill(parameters)
retainCycle = nil
private func bytesToHexString(bytes: [UInt8]) -> String
return bytes.mapString(format: "%02X", $0).joined(separator: "")
【问题讨论】:
【参考方案1】:Promise 只能实现一次,因此只适用于实现一次的系统。对于像套接字这样的东西,你应该使用另一种异步模式,比如完成块。
【讨论】:
以上是关于PromiseKit 4 - 包装委托的主要内容,如果未能解决你的问题,请参考以下文章