— Android, Mobile — 1 min read
1// The DataSource is just an interface which define which function2interface 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.
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, 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}
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 source4 }
Kotlin Coroutines with Architecture Component Live Data ViewMOdel Lifecycle