Created
July 9, 2018 06:44
-
-
Save yaraki/ec34b4a25b569cb7896765dfc848c859 to your computer and use it in GitHub Desktop.
LiveData + Kotlin Coroutines
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
| 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()) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
createLiveDataare executed at the time ofonInactive.createLiveData(such asiingenerateCounter) are retained as far as the LiveData is retained.