Skip to content

A lightweight extension to subscribe Starscream websocket events with RxSwift

License

Notifications You must be signed in to change notification settings

LukeWei/RxStarscream

 
 

Repository files navigation

🙋 Note: This project is my personal update to support SPM and the new version of Starscream.

RxStarscream

CircleCI pod Carthage compatible

A lightweight extension to Starscream to track websocket events using RxSwift observables.

Installation

CocoaPods

RxStarscream is available through CocoaPods. Add the following line to your Podfile:

pod 'RxStarscream'

Then run:

pod install

RxStarscream version vs Swift version.

Below is a table that shows which version of RxStarscream you should use for your Swift version.

Swift RxStarscream RxSwift
>= 5.0 >= 0.11 >= 6.6.0
>= 4.2 >= 0.10 >= 4.3
< 4.2 >= 0.8 >= 4.0
3.X 0.7 3.0.0 - 3.6.1

Swift Package manager

Create a Package.swift file

let package = Package(
        name: "SampleApp",

        dependencies: [
            .package(url: "https://github.com/RxSwiftCommunity/RxStarscream.git",
                     from: "0.11.0"),
        ],

        targets: [
            .target(
                    name: "SampleApp",
                    dependencies: ["RxStarscream"])
        ]
)

Usage examples

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: URL(string: "ws://localhost:8080/")!)
socket.connect()

Now you can subscribe e.g to all of the websocket events:

socket.rx.response.subscribe(onNext: { (response: WebSocketEvent) in
	switch response {
	case .connected:
		print("Connected")
	case .disconnected(let error):
		print("Disconnected with optional error : \(error)")
	case .text(let text):
		print("Message : \(text)")
	case .data(_):
		print("Data")
	case .pong:
		print("Pong")
  	}
}).disposed(by: disposeBag)

Or just to a connect event:

socket.rx.connected.subscribe(onNext: { (isConnected: Bool) in
	print("Is connected : \(isConnected)")
}).disposed(by: disposeBag)

Or just to a message event:

socket.rx.text.subscribe(onNext: { (message: String) in
	print("Message : \(message)")
}).disposed(by: disposeBag)

Sample Project

There's a sample project with SPM.

The sample project uses echo server - https://www.websocket.org/echo.html

Have fun!

Thanks

Everyone in the RxSwift Slack channel.

Contributing

Bug reports and pull requests are welcome.

License

RxStarscream is available under the MIT license. See the LICENSE file for more info.

About

A lightweight extension to subscribe Starscream websocket events with RxSwift

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 84.8%
  • Ruby 7.9%
  • Objective-C 5.3%
  • Shell 2.0%