Skip to content
KYND Dev

Notes on Kotlin Coroutines with Live Data in Android

Android, Mobile1 min read

1// The DataSource is just an interface which define which function
2interface DataSource {
3 fun getCurrentTime(): LiveData<Long>
4 fun fetchWeather(): LiveData<String>
5 val cachedData: LiveData<String>
6 suspend fun fetchNewData()
7}
8
9// DefaultDataSource is the default implementation of DataSource

CoroutineLiveData: Allow controlling a LiveData from a coroutine block.

LiveData builder that emits values:

1// When observed, it generates a new value every second.
2 fun getCurrentTime(): LiveData<Long> =
3 liveData {
4 while (true) {
5 emit(System.currentTimeMillis())
6 delay(1000)
7 }
8 }

Transformation

Transformation, like map and switchMap are running in the UI thread. However, Combining of switchMap with liveData builder can help us call suspend functions or move the transformation to different thread.

1val currentTimeTransformed = currentTime.switchMap {
2 liveData(defaultDispatcher) { emit(timeStampToTime(it)) }
3}

Using emit and emitSource

We can update one liveData from another LiveData using emitSource:

1val currentWeather: Live<String> = liveData{
2 emit("Loading...")
3 emitSource(dataSource.fetchWeather()) // this will emit value from other source
4 }

Reference

Kotlin Coroutines with Architecture Component Live Data ViewMOdel Lifecycle