我对 Rx 非常陌生,并且一直在尝试制作一个解析服务的 Bonjour 发现客户端。这很简单,但我想尝试使用 RxSwift。
由于发现的 NSNetService 对象需要在解析之前持久化,所以我不得不进行嵌套订阅调用,外部订阅调用用于发现,内部调用用于解析……但有些事情告诉我这不是最好的方法。
import UIKit
import RxSwift
class BonjourClient: NSObject {
let disposeBag = DisposeBag()
var servicesArray = [NSNetService]()
func startBrowsing() {
let browser = NSNetServiceBrowser()
browser.rx_netServiceBrowserDidFindServiceMoreComing
.subscribeNext { (service: NSNetService) in
self.servicesArray.append(service)
self.servicesArray.last!.rx_netServiceDidResolveAddress
.subscribeNext { (sender: NSNetService) in
print("Resolved \(sender.name)")
let data = sender.TXTRecordData()
let dict: [String: NSData?] = NSNetService.dictionaryFromTXTRecordData(data!)
for (key, value) in dict {
print("\(key) : \(String(data: value!, encoding: NSUTF8StringEncoding)!)")
}
}.addDisposableTo(self.disposeBag)
self.servicesArray.last!.resolveWithTimeout(5)
}.addDisposableTo(disposeBag)
browser.searchForServicesOfType("_amzn-wplay._tcp.", inDomain: "local.")
NSRunLoop.currentRunLoop().run()
}
}
我的代理类如下:
import UIKit
import RxSwift
import RxCocoa
class RxNSNetServiceBrowserDelegateProxy: DelegateProxy, NSNetServiceBrowserDelegate, DelegateProxyType {
static func currentDelegateFor(object: AnyObject) -> AnyObject? {
let browser: NSNetServiceBrowser = object as! NSNetServiceBrowser
return browser.delegate
}
static func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let browser: NSNetServiceBrowser = object as! NSNetServiceBrowser
browser.delegate = delegate as? NSNetServiceBrowserDelegate
}
}
class RxNSNetServiceDelegateProxy: DelegateProxy, NSNetServiceDelegate, DelegateProxyType {
static func currentDelegateFor(object: AnyObject) -> AnyObject? {
let service: NSNetService = object as! NSNetService
return service.delegate
}
static func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let service: NSNetService = object as! NSNetService
service.delegate = delegate as? NSNetServiceDelegate
}
}
extension NSNetServiceBrowser {
public var rx_delegate: DelegateProxy {
return proxyForObject(RxNSNetServiceBrowserDelegateProxy.self, self)
}
public var rx_netServiceBrowserDidFindServiceMoreComing: Observable<NSNetService> {
return rx_delegate.observe("netServiceBrowser:didFindService:moreComing:")
.map { params in
let service = params[1] as! NSNetService
return service
}
}
}
extension NSNetService {
public var rx_delegate: DelegateProxy {
return proxyForObject(RxNSNetServiceDelegateProxy.self, self)
}
public var rx_netServiceDidResolveAddress: Observable<NSNetService> {
return rx_delegate.observe("netServiceDidResolveAddress:")
.map { params in
return params[0] as! NSNetService
}
}
}
如果我flatMap
在browser.rx_netServiceBrowserDidFindServiceMoreComing
调用之后使用而不是subscribeNext
,则服务将无法解析,因为我无法从内部将其持久化到数组中flatMap
,原因是我无法理解,主要是因为从未接触过 Rx。我一定要使用嵌套调用吗?
我的问题的简短版本是上述作品,但对我来说似乎很复杂。任何想法将不胜感激。