处置时如何调用方法

时间:2019-02-01 10:07:45

标签: rx-swift

我在RxSwift中有这段代码包装了UDPBroadcastConnection(https://github.com/gunterhager/UDPBroadcastConnection) 我的问题是,在放置可观察对象时,我该怎么办才能调用closeConnection()?

struct UDPBroadcastResponse {
    let ip: String
    let port: Int
    let message: [UInt8]
}

final class RxBroadcaster: UDPBroadcastConnection {
    let response = PublishSubject<UDPBroadcastResponse>()
    private let disposeBag = DisposeBag()
}

extension RxBroadcaster: ReactiveCompatible {}

extension Reactive where Base: RxBroadcaster {
    func send(message: String) -> Observable<UDPBroadcastResponse> {
        DDLogVerbose("Sending UDP broadcast message: \(message)")
        self.base.sendBroadcast(message)
        return self.base.response
    }
}

extension RxBroadcaster {
    convenience init(port: UInt16) {
        let rely = ReplaySubject<UDPBroadcastResponse>.createUnbounded()
        self.init(port: port) { ip, port, message in
            let response = UDPBroadcastResponse(ip: ip, port: port, message: message)
            // DDLogVerbose("Receiving UDP message: IP: \(response.ip). Port: \(response.port). Message: \(response.message.map{ String(format: "%02X", $0) }.joined())")
            DDLogVerbose("Receiving UDP message: IP: \(response.ip). Port: \(response.port)")
            rely.onNext(response)
        }
        rely.bind(to: self.response).disposed(by: disposeBag)
    }
}

在这里我看到一个示例:http://adamborek.com/practical-introduction-rxswift/ 但是我不确定所涉及对象的生命周期。 你能帮助我吗? 感谢您的建议。

2 个答案:

答案 0 :(得分:1)

您可以使用do运算符挂接到订阅的生命周期事件并执行副作用。订阅或绑定之前,可以在Observable链中的任何位置调用do。示例:

rely.do(onDispose: {
    // called as your subscription is being disposed
}).bind(to: self.response).disposed(by: disposeBag)

答案 1 :(得分:0)

我更倾向于这样实现RxBroadcaster:

final class RxBroadcaster {
    let response: Observable<UDPBroadcastResponse>

    init(port: UInt16) {
        let _response = PublishSubject<UDPBroadcastResponse>()
        let _connection = UDPBroadcastConnection(port: port, handler: { ipAddress, port, response in
            _response.onNext(UDPBroadcastResponse(ip: ipAddress, port: port, message: response))
        })

        response = _response.asObservable()
        completion = _response.asObserver()
        connection = _connection
    }

    deinit {
        connection.closeConnection()
        completion.onCompleted()
    }

    private let connection: UDPBroadcastConnection
    private let completion: AnyObserver<UDPBroadcastResponse>
}

extension RxBroadcaster: ObserverType {
    public func on(_ event: RxSwift.Event<Data>) {
        guard case let .next(data) = event else { return }
        connection.sendBroadcast(data)
    }
}

现在,您可以通过绑定到RxBroadcaster myData.bind(to: myBroadcaster)来发送数据,并通过订阅广播公司的响应来接收数据。当广播公司超出范围时,连接自然会关闭。

像您一样,做一个呼叫/响应操作员对我来说有点奇怪。 UDP套接字的关键是您将获得与发送的消息无关的消息。