sockets – How to connect via WebSocket on Android using Scarlet?-ThrowExceptions

Exception or error:

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"
How to solve:

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())
    })

###

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"

Leave a Reply

Your email address will not be published. Required fields are marked *