Kotlin Flow vs LiveData
Asked Answered
P

3

40

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.

Pulsar answered 16/11, 2019 at 11:14 Comment(0)
D
25

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

  • Generally a regular flow is not lifecycle aware but liveData is lifecyle aware. ( we can use stateFlow in conjunction with repeatOnLifecycle to make it lifecycle aware )
  • flow has got a bunch of different operators which livedata doesn't have !

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

Daciadacie answered 9/12, 2019 at 11:2 Comment(1)
It is important to note that Coroutines now has the StateFlow class. This class is very similar to the LiveData class, in that the value can be accessed directly from any context, and any changes are automatically emitted to any observers. But because it is a Flow object, it means all of the nice coroutines operators are available.Etheridge
S
9

As the name suggests, you can think of Flow like a continuous flow of multiple asynchronously computed values. The main difference between LiveData and Flow, from my point of view, is that a Flow continuously emits results while LiveData will update when all the data is fetched and return all the values at once. In your example you are fetching single values, which is not exactly what Flow was dsigned for [update: use StateFlow for that].

I don't have a Room example but let's say you are rendering something that takes time, but you wanna display results while rendering and buffering the next results.

private fun render(stuffToPlay: List<Any>): Flow<Sample> = flow {
     val sample = Sample()
     // computationally intensive operation on stuffToPlay
     Thread.sleep(2000)
     emit(sample)
}

Then in your 'Playback' function you can for example display the results where stuffToPlay is a List of objects to render, like:

playbackJob = GlobalScope.launch(Dispatchers.Default) {
            
    render(stuffToPlay)
        .buffer(1000)   // tells the Flow how many values should be calculated in advance
            
        .onCompletion {
            // gets called when all stuff got played
        }
        .collect{sample ->
           // collect the next value in the buffered queue
           // e.g. display sample
        }
}

An important characteristic of Flow is that it's builder code (here render function) only gets executed, when it gets collected, hence its a cold stream.

You can also refer to the docs at Asynchronous Flow

Stipend answered 16/11, 2019 at 16:9 Comment(0)
S
8

Considering that Flow is part of Kotlin and LiveData is part of the androidx.lifecycle library, I think that Flow is used as part of the uses cases in clean architecture (without dependencies to the framework).

LiveData, on the other hand, is lifecycle aware, so is a match with ViewModel

I have all my architecture using livedata at this moment, but Flow looks like an interesting topic to study and adopt.

Shaunteshave answered 14/9, 2020 at 0:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.