A lightweight extension to Starscream to track websocket events using RxSwift observables.
RxStarscream is available through CocoaPods.
Add the following line to your Podfile
:
pod 'RxStarscream'
Then run:
pod install
Add this to your Cartfile
github "RxSwiftCommunity/RxStarscream"
Then run:
carthage update
After installing via CococPods or Carthage, you should import the framework.
import RxStarscream
Once imported, you can open a connection to your WebSocket server.
socket = WebSocket(url: NSURL(string: "ws://localhost:8080/")!)
socket.connect()
Now you can subscribe e.g to all of the websocket events:
socket.rx.response.subscribeNext { (response: WebSocketEvent) in
switch response {
case .Connected:
print("Connected")
case .Disconnected(let error):
print("Disconnected with optional error : \(error)")
case .Message(let msg):
print("Message : \(msg)")
case .Data(_):
print("Data")
case .Pong:
print("Pong")
}
}.addDisposableTo(disposeBag)
Or just to a connect event:
socket.rx.connected.subscribeNext { (isConnected: Bool) in
print("Is connected : \(isConnected)")
}.addDisposableTo(self.disposeBag)
Or just to a message event:
socket.rx_text.subscribeNext { (message: String) in
print("Message : \(message)")
}.addDisposableTo(self.disposeBag)
There's a sample project (you need to run carthage update
for it to compile).
Tne sample project use echo server - https://www.websocket.org/echo.html
Have fun!
Everyone in the RxSwift Slack channel.
Bug reports and pull requests are welcome.
RxStarscream is available under the MIT license. See the LICENSE file for more info.