如何使用Scarlet连接到Android上的websocket?

时间:2019-07-02 07:44:36

标签: android sockets kotlin client

    val scarletInstance = Scarlet.Builder()
    .webSocketFactory(okHttpClient.newWebSocketFactory(GDAX_URL))
    .addMessageAdapterFactory(MoshiMessageAdapter.Factory())
    .addStreamAdapterFactory(RxJava2StreamAdapterFactory())
    .build() 

实现'com.tinder.scarlet:scarlet:0.1.8'

implementation "com.github.tinder.scarlet:scarlet-websocket-okhttp:0.1.7"
implementation "com.github.tinder.scarlet:scarlet-stream-adapter-rxjava2:0.2.4"
implementation "com.github.tinder.scarlet:scarlet-message-adapter-moshi:0.2.4"
implementation "com.github.tinder.scarlet:scarlet-lifecycle-android:0.2.4"

2 个答案:

答案 0 :(得分:3)

由于类重复,您的代码失败。由于不同的lib版本而发生。正确的实现是:

//web sockets
implementation 'com.tinder.scarlet:scarlet:0.1.10'
implementation "com.tinder.scarlet:websocket-okhttp:0.1.10"
implementation "com.tinder.scarlet:stream-adapter-rxjava2:0.1.10"
implementation "com.tinder.scarlet:message-adapter-moshi:0.1.10"
implementation "com.tinder.scarlet:lifecycle-android:0.1.10"

答案 1 :(得分:0)

首先,您应该使用接口声明WebSocket客户端。使用@Receive@Send之类的猩红色注释来定义如何处理WebSocket通信,如以下示例所示:

interface NewsService {
    @Receive
    fun observeWebSocketEvent(): Flowable<WebSocket.Event>
    @Send
    fun sendSubscribe(subscribe: Subscribe)
    @Receive
    fun observeNews(): Flowable<MyNews>
}  

下一步是创建Scarlet接口的实现,并订阅在WebSocket连接期间发出的数据流。在下面的示例中,使用了Moshi和RxJava,但是Scarlet提供了其他方式来处理和操作数据。

val scarletInstance = Scarlet.Builder()
    .webSocketFactory(okHttpClient.newWebSocketFactory(BASE_URL))
    .addMessageAdapterFactory(MoshiMessageAdapter.Factory())
    .addStreamAdapterFactory(RxJava2StreamAdapter.Factory())
    .build()

//service created
val newsService = scarletInstance.create<NewsService>()

//define websocket event observer
newsService.observeWebSocketEvent()
    .filter { it is WebSocket.Event.OnConnectionOpened<*> }
    .subscribe({
        newsService.sendSubscribe()
    })

// news data result
newsService.observeNews()
    .subscribe({ news ->
        Log.d(TAG, news.toString())
    })