Skip to content

Instantly share code, notes, and snippets.

@yaraki
Created July 9, 2018 06:44
Show Gist options
  • Save yaraki/ec34b4a25b569cb7896765dfc848c859 to your computer and use it in GitHub Desktop.
Save yaraki/ec34b4a25b569cb7896765dfc848c859 to your computer and use it in GitHub Desktop.
LiveData + Kotlin Coroutines
package io.github.yaraki.coroutineex
import android.arch.lifecycle.LiveData
import android.content.Context
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.SendChannel
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.yield
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.concurrent.TimeUnit
fun <E> createLiveData(
block: suspend SendChannel<E>.() -> Unit
): LiveData<E> {
return object : LiveData<E>() {
private var receivingJob: Job? = null
private var sendingJob: Job? = null
override fun onActive() {
super.onActive()
val channel = Channel<E>()
receivingJob = launch(UI) {
for (e in channel) {
value = e
yield()
}
}
sendingJob = launch {
channel.block()
}
}
override fun onInactive() {
super.onInactive()
sendingJob?.cancel()
receivingJob?.cancel()
}
}
}
fun currentTime() = createLiveData {
while (true) {
send(System.currentTimeMillis().toString())
delay(300L, TimeUnit.MILLISECONDS)
}
}
fun generateCounter(): LiveData<String> {
var i = 0
return createLiveData {
while (true) {
send(i.toString())
i++
delay(300L, TimeUnit.MILLISECONDS)
}
}
}
fun loadText(context: Context, filename: String) = createLiveData {
BufferedReader(InputStreamReader(context.assets.open(filename))).use { reader ->
send(reader.readLine())
}
}
@yaraki
Copy link
Author

yaraki commented Jul 9, 2018

  • Finally-clauses in createLiveData are executed at the time of onInactive.
  • Variables outside of createLiveData (such as i in generateCounter) are retained as far as the LiveData is retained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment