Created
April 12, 2020 09:54
-
-
Save manoamaro/c562b05d03b4826f8754f89ef361d132 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
fun getEventsFlow(): Flow<Event> = flow { | |
coroutineScope { // Wrap the code with this, to have access to the coroutine scope | |
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 while the coroutine is active | |
while (isActive) { | |
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