Created
April 5, 2020 13:45
-
-
Save manoamaro/48c04a55239e52cc295ca2faa5f77bca to your computer and use it in GitHub Desktop.
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
data class Event(val name: String = "", val data: String = "") | |
fun getEventsFlow(): Flow<Event> = flow { | |
val url = "https://hacker-news.firebaseio.com/v0/updates.json" | |
// Gets HttpURLConnection. Blocking function. Should run in background | |
val conn = (URL(url).openConnection() as HttpURLConnection).also { | |
it.setRequestProperty("Accept", "text/event-stream") // set this Header to stream | |
it.doInput = true // enable inputStream | |
} | |
conn.connect() // Blocking function. Should run in background | |
val inputReader = conn.inputStream.bufferedReader() | |
var event = Event() | |
// run forever | |
while (true) { | |
val line = inputReader.readLine() // Blocking function. Read stream until \n is found | |
when { | |
line.startsWith("event:") -> { // get event name | |
event = event.copy(name = line.substring(6).trim()) | |
} | |
line.startsWith("data:") -> { // get data | |
event = event.copy(data = line.substring(5).trim()) | |
} | |
line.isEmpty() -> { // empty line, finished block. Emit the event | |
emit(event) | |
event = Event() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment