Thomas Nordmeyer
10/10/2019, 5:52 PMval contract: LiveData<Contract?> = MutableLiveData()
val authState: LiveData<AuthState?> = MutableLiveData()
init {
contract.observeForever { contract ->
(authState as MutableLiveData).value = when {
tokenRepository.tokens.accessToken.isNullOrEmpty() -> AuthState.ANONYMOUS
contract != null -> AuthState.LOGGED_IN_WITH_CONTRACT
else -> AuthState.LOGGED_IN_WITHOUT_CONTRACT
}.also { authState ->
Timber.d("Refreshing auth state to $authState after contract live data update")
}
}
}
But this doesn't
val contract: LiveData<Contract?> = MutableLiveData()
val authState = Transformations.map(contract)
{
when {
tokenRepository.tokens.accessToken.isNullOrEmpty() -> AuthState.ANONYMOUS
contract != null -> AuthState.LOGGED_IN_WITH_CONTRACT
else -> AuthState.LOGGED_IN_WITHOUT_CONTRACT
}.also { authState ->
Timber.d("Refreshing auth state to $authState after contract live data update")
}
}
init {
contract.observeForever { Timber.d("Updated contract value to ${it?.contract}")}
}
I would expect the logs from the observer in init method be followed trom the Transformations observer always. But sometimes I get the init method's only (setting contract.value=null).wasyl
10/10/2019, 9:20 PMauthState
?wasyl
10/10/2019, 9:20 PMThomas Nordmeyer
10/11/2019, 7:53 AMwasyl
10/11/2019, 8:00 AMauthState.observeForever { }
, then you can do getValue()
and actually get the valueThomas Nordmeyer
10/11/2019, 8:36 AM// run as androidTest
class LiveDataTryoutTest {
@get:Rule
val rule = InstantTaskExecutorRule()
@Test
fun test() {
val d = MutableLiveData<String>()
val t = Transformations.map(d) {
d.value?.length
}
d.postValue("a")
assertEquals("a", d.value)
assertEquals(1, t.value) // fails
}
}
wasyl
10/11/2019, 8:41 AMThomas Nordmeyer
10/11/2019, 8:53 AMThomas Nordmeyer
10/11/2019, 8:56 AMwasyl
10/11/2019, 8:58 AMInternal values could sill update without danger.the idea was that they would update and consume resources unnecessarily. If the value gets updated 10 times when the view is in background, it doesn’t make sense to run 10 transformations if only the last one will be delivered to the view
Thomas Nordmeyer
10/11/2019, 8:59 AMThomas Nordmeyer
10/11/2019, 9:01 AMJohn
10/14/2019, 3:34 PMfun <T> LiveData<T>.fetch(): T? {
var value: T? = null
val obs = Observer<T> { t -> value = t }
this.observeForever(obs)
this.removeObserver(obs)
return value
}