Ad

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"
Ad

Answer

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())
    })
Ad
source: stackoverflow.com
Ad