Skip to content

Instantly share code, notes, and snippets.

Created April 23, 2022 20:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Complete Code
class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
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) {
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)
val request = Request.Builder()
.header("Accept", "application/json; q=0.5")
.addHeader("Accept", "text/event-stream")
.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