Created
April 23, 2022 20:28
-
-
Save hiteshchopra11/356d299b5bc5189bdfd16c84fd29bbe8 to your computer and use it in GitHub Desktop.
Complete Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
companion object { | |
private const val TAG = "MainActivity" | |
} | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val eventSourceListener = object : EventSourceListener() { | |
override fun onOpen(eventSource: EventSource, response: Response) { | |
super.onOpen(eventSource, response) | |
Log.d(TAG, "Connection Opened") | |
} | |
override fun onClosed(eventSource: EventSource) { | |
super.onClosed(eventSource) | |
Log.d(TAG, "Connection Closed") | |
} | |
override fun onEvent( | |
eventSource: EventSource, | |
id: String?, | |
type: String?, | |
data: String | |
) { | |
super.onEvent(eventSource, id, type, data) | |
Log.d(TAG, "On Event Received! Data -: $data") | |
} | |
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) { | |
super.onFailure(eventSource, t, response) | |
Log.d(TAG, "On Failure -: ${response?.body}") | |
} | |
} | |
val client = OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS) | |
.readTimeout(10, TimeUnit.MINUTES) | |
.writeTimeout(10, TimeUnit.MINUTES) | |
.build() | |
val request = Request.Builder() | |
.url("https://test-sse-backend.herokuapp.com/events") | |
.header("Accept", "application/json; q=0.5") | |
.addHeader("Accept", "text/event-stream") | |
.build() | |
EventSources.createFactory(client) | |
.newEventSource(request = request, listener = eventSourceListener) | |
lifecycleScope.launchWhenCreated { | |
withContext(Dispatchers.IO) { | |
client.newCall(request).enqueue(responseCallback = object : Callback { | |
override fun onFailure(call: Call, e: IOException) { | |
Log.e(TAG, "API Call Failure ${e.localizedMessage}") | |
} | |
override fun onResponse(call: Call, response: Response) { | |
Log.d(TAG, "APi Call Success ${response.body.toString()}") | |
} | |
}) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment