Skip to main content

LiveDataのemitとemitSourceの違い

Codelabを実施していてLiveDataでemitとemitSourceがあることに気づいた
そんなデータの排出方法の違いについて調べてみた


・emit
データを送る場合はemitを使う
ちなみにLiveDataの中からsuspend functionは呼べるらしい
これ知らなかった

val user: LiveData<User> = liveData {
    val data = database.loadUser()
    emit(data)
}

 

・emitSource
emitSourceはLitveDataを返却する
これでデータを複数送ることができる
なので元データを送るので二度送る必要はない

liveData {
    emitSource(database.loadUser())
}

 

・参考
https://developer.android.com/topic/libraries/architecture/coroutines?hl=ja
https://stackoverflow.com/questions/58546944/what-is-the-difference-between-emit-and-emitsource-with-livedata-as-in-real
https://developer.android.com/topic/libraries/architecture/coroutines?hl=ja

関連記事:

Pocket