SettingsLiveData: post initial value even when it's null (#686)

This commit is contained in:
Ricki Hirner 2024-03-28 09:44:19 +01:00 committed by GitHub
parent d0e5bbc0ad
commit 9b47427b66
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 18 additions and 1 deletions

View file

@ -5,6 +5,7 @@
package at.bitfire.davdroid.settings
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.map
import at.bitfire.davdroid.TestUtils.getOrAwaitValue
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
@ -60,6 +61,20 @@ class SettingsManagerTest {
}
@Test
fun test_getBooleanLive_initialValuePostedEvenWhenNull() {
val live = settingsManager.getBooleanLive(SETTING_TEST).map { value ->
value
}
assertNull(live.getOrAwaitValue())
// posts value to main thread, InstantTaskExecutorRule is required to execute it instantly
settingsManager.putBoolean(SETTING_TEST, true)
runBlocking(Dispatchers.Main) { // observeForever can't be run in background thread
assertTrue(live.getOrAwaitValue()!!)
}
}
@Test
fun test_getBooleanLive_getValue() {
val live = settingsManager.getBooleanLive(SETTING_TEST)

View file

@ -178,6 +178,8 @@ class SettingsManager internal constructor(
inner class SettingLiveData<T>(
val getValueOrNull: () -> T?
): LiveData<T>(), OnChangeListener {
private var hasValue = false
override fun onActive() {
addOnChangeListener(this)
update()
@ -194,7 +196,7 @@ class SettingsManager internal constructor(
@Synchronized
private fun update() {
val newValue = getValueOrNull()
if (value != newValue)
if (!hasValue || value != newValue)
postValue(newValue)
}
}