Search code examples
javaandroidokhttpserver-sent-events

Passing values from okhttp-eventsource BackgroundEventHandler to Main Thread


I'm trying to use okhttp-eventsource lib to handle Service Sent Events in my Android App but I can't figure out how to pass the values received from the onMessage() method to my Main Thread. This is my goal: everytime a new JSON is posted to my server I would like to get it and process it on my Main Thread.

This is what my code looks like but it's not working. BackgroundEventHandler.onMessage() method prints on the log the received message, but I get NetworkOnMainThreadException on the Main Thread even if .messages() method should just return an iterable sequence of SSE messages.

BackgroundEventHandler.java

...
public void onMessage(String event, MessageEvent messageEvent){
        Log.d(TAG, messageEvent.getData().toString());
    }
...

MainActivity.java

...
private void newThingCreated() throws MalformedURLException{
        BackgroundEventSource bes = new BackgroundEventSource.Builder(tcHandler,
                new EventSource.Builder(
                        ConnectStrategy.http(explorer.createQueryUrl("/events/thing_created"))
                                .connectTimeout(10, TimeUnit.SECONDS)
                        // connectTimeout and other HTTP options are now set through
                        // HttpConnectStrategy
                )
        )
                .threadPriority(Thread.MAX_PRIORITY)
                // threadPriority, and other options related to worker threads,
                // are now properties of BackgroundEventSource
                .build();
        bes.start();
        bes.getEventSource().messages().forEach(new Consumer<MessageEvent>() {
            @Override
            public void accept(MessageEvent messageEvent) {
                Log.d(TAG, messageEvent.toString());
            }
        });
    }
...

tcHandler is my BackgroundEventHandler.

Thanks in advance!


Solution

  • Solved using another library: https://github.com/AndroidDeveloper98/ServerSentEventsAndroid which implements a listener. Here's my onMessage() method implementation:

     @Override
        public void onMessage(ServerSentEvent sse, String id, String event, String message) {
            Log.d(TAG, "EVENT: " + event);
            lastEventId = id;
            switch(event) {
                case "thing_created":
                    consumeExploredThing(Thing.fromJson(message));
                    break;
                case "thing_updated":
                    Log.d(TAG, message);
                    break;
                case "thing_deleted":
                    try{
                        JSONObject jsonObject = new JSONObject(message);
                        deleteDiscoveredThing(jsonObject.getString("id"));
                    } catch (JSONException ex) {
                        ex.printStackTrace();
                    }
                    break;
                default:
                    Log.d(TAG, "ERROR!");
            }
        }