Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect via WebSocket on Android using Scarlet?

Code from README.md

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

Version and dependencies:

implementation '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"
like image 501
Sanam Yavarpor Avatar asked Jul 02 '19 07:07

Sanam Yavarpor


2 Answers

First of all, you should declare a WebSocket client using an interface. Use Scarlet annotations such as @Receive and @Send to define how you are going to handle the WebSocket communication, as the following example:

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

Next step is create an implementation of your Scarlet Interface and subscribe the data stream emitted during the WebSocket connection. In the following example , Moshi and RxJava are being used however Scarlet provide other ways to handle and manipulate the data.

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())
    })
like image 171
Agna JirKon Rx Avatar answered Oct 21 '22 13:10

Agna JirKon Rx


Your code is FAILING due to class duplication. It occurs because of different lib versions. The correct implementation is:

//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"
like image 23
v.podlipnyak Avatar answered Oct 21 '22 11:10

v.podlipnyak