androidkotlinandroid-livedatakotlin-coroutineskotlinx.coroutines.flow

Kotlin Flow vs LiveData


In the last Google I/O, Jose Alcerreca and Yigit Boyar told us that we should no longer use LiveData to fetch data. Now we should use suspend functions for one-shot fetches and use Kotlin's Flow to create a data stream. I agree that coroutines are great for one-shot fetching or other CRUD operations, such as inserting, etc. But in cases where I need a data stream, I don’t understand what advantages Flow gives me. It seems to me that LiveData is doing the same.

Example with Flow:

ViewModel

val items = repository.fetchItems().asLiveData()

Repository

fun fetchItems() = itemDao.getItems()

Dao

@Query("SELECT * FROM item")
fun getItems(): Flow<List<Item>>

Example with LiveData:

ViewModel

val items = repository.fetchItems()

Repository

fun fetchItems() = itemDao.getItems()

Dao

@Query("SELECT * FROM item")
fun getItems(): LiveData<List<Item>>

I would also like to see some examples of projects using coroutines and Flow to work with the Room or Retrofit. I found only a Google's ToDo sample where coroutines are used for one-shot fetching and then manually refetch data on changing.


Solution

  • Flow is sort of a reactive stream ( like rxjava ). There are a bunch of different operators like .map, buffer() ( anyway fewer operators compared to rxJava ). So, one of the main differences between LiveData and Flow is that you can execute the map computation / transformation in some other thread using

     flowOn(Dispatcher....). 
    

    So, for example :-

     flowOf("A","B","C").map { compute(it) }.flowOn(Dispatchers.IO).collect {...} // U can change the execution thread of the computation ( by default it is in the same dispatcher as collect )
    

    With LiveData and map , the above can't be achieved directly !

    So it is recommended to keep flow in the repository level , and make the livedata a bridge between the UI and the repository !

    The main difference is that

    But again , Its up to u how u wanna construct your project !