MutableLiveDataとShopify/livedata-ktxのPublishLiveDataKtxとLiveEventの挙動メモ

自分用のMutableLiveDataとShopify/livedata-ktxのPublishLiveDataKtxとLiveEventの比較です。


observe時

根本のLiveData
値が来るか?

MutableLiveData

LiveEvent

PublishLiveDataKtx(SingleLiveData)


同じ値が代入されたとき

根本のLiveData
値が来るか?

MutableLiveData

LiveEvent

PublishLiveDataKtx(SingleLiveData)


onStart() かつ 値変更なし

根本のLiveData
値が来るか?

MutableLiveData

LiveEvent

PublishLiveDataKtx(SingleLiveData)


onStart() かつ onStop中に同じ値が代入されたとき

根本のLiveData
値が来るか?

MutableLiveData

LiveEvent

PublishLiveDataKtx(SingleLiveData)


onStart() かつ onStop中に違う値が代入されたとき

根本のLiveData
値が来るか?

MutableLiveData

LiveEvent

PublishLiveDataKtx(SingleLiveData)


liveData.distinctUntilChanged() かつ onStop中に違う値が代入されたとき

根本のLiveData
値が来るか?

MutableLiveData

LiveEvent

PublishLiveDataKtx(SingleLiveData)


コード

object Singleton {

val changingLiveData = MutableLiveData<Int>().apply {
thread {
var i = 0
while (true) {
postValue(i++)
Thread.sleep(5000L)
}
}
}

val sameValueChangeLiveData = MutableLiveData<Int>().apply {
thread {
val i = 0
while (true) {
postValue(i)
Thread.sleep(5000L)
}
}
}

val noChangeLiveData = MutableLiveData<Int>().apply {
value = 1
}

val changingPublishLiveData = PublishLiveDataKtx<Int>().apply {
thread {
var i = 0
while (true) {
postValue(i++)
Thread.sleep(5000L)
}
}
}

val sameValueChangePublishLiveData = PublishLiveDataKtx<Int>().apply {
thread {
val i = 0
while (true) {
postValue(i)
Thread.sleep(5000L)
}
}
}

val noChangePublishLiveData = PublishLiveDataKtx<Int>().apply {
value = 1
}

val changingLiveEvent = LiveEvent<Int>().apply {
thread {
var i = 0
while (true) {
postValue(i++)
Thread.sleep(5000L)
}
}
}

val sameValueChangeLiveEvent = LiveEvent<Int>().apply {
thread {
val i = 0
while (true) {
postValue(i)
Thread.sleep(5000L)
}
}
}

val noChangeLiveEvent = LiveEvent<Int>().apply {
value = 1
}
}

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
observe("changingLiveData", Singleton.changingLiveData)
observe("sameValueChangeLiveData", Singleton.sameValueChangeLiveData)
observe("noChangeLiveData", Singleton.noChangeLiveData)
observe("changingPublishLiveData", Singleton.changingPublishLiveData)
observe("sameValueChangePublishLiveData", Singleton.sameValueChangePublishLiveData)
observe("noChangePublishLiveData", Singleton.noChangePublishLiveData)
observe("changingLiveEvent", Singleton.changingLiveEvent)
observe("sameValueChangeLiveEvent", Singleton.sameValueChangeLiveEvent)
observe("noChangeLiveEvent", Singleton.noChangeLiveEvent)
}

fun observe(name: String, liveData: LiveData<Int>) {
liveData.observe(this) {
Log.d("livedata test", "${liveData.javaClass.simpleName}: $name: data:$it")
}
liveData.distinctUntilChanged().observe(this) {
Log.d("livedata test", "${liveData.javaClass.simpleName}: $name: data distinct:$it")
}
}
}