Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between emit and emitSource with LiveData ? ( as in REAL time USE-CASE )

emit accepts the data class whereas emitSource accepts LiveData<T> ( T -> data ). Considering the following example :- I have two type of calls :-

suspend fun getData(): Data // returns directly data

and the other one ;

suspend fun getData(): LiveData<Data> // returns live data instead

For the first case i can use:-

liveData {
   emit(LOADING)
   emit(getData())
}

My question : Using the above method would solve my problem , WHY do we need emitSource(liveData) anyway ?

Any good use-case for using the emitSource method would make it clear !

like image 524
Santanu Sur Avatar asked Oct 24 '19 18:10

Santanu Sur


2 Answers

As you mentioned, I don't think it solves anything in your stated problem, but I usually use it like this:

If I want to show cached data to the user from the db while I get fresh data from remote, with only emit it would look something like this:

liveData{
    emit(db.getData())
    val latest = webService.getLatestData()
    db.insert(latest)
    emit(db.getData())
}

But with emitSource it looks like this:

liveData{
    emitSource(db.getData())
    val latest = webService.getLatestData()
    db.insert(latest)
}

Don't need to call emit again since the liveData already have a source.

like image 136
Peter Avatar answered Oct 06 '22 13:10

Peter


From what I understand emit(someValue) is similar to myData.value = someValue whereas emitSource(someLiveValue) is similar to myData = someLiveValue. This means that you can use emit whenever you want to set a value once, but if you want to connect your live data to another live data value you use emit source. An example would be emitting live data from a call to room (using emitSource(someLiveData)) then performing a network query and emitting an error (using emit(someError)).

like image 15
Myk Avatar answered Oct 06 '22 13:10

Myk