I am using databinding to display text on TextView using ternary syntax.
android:text="@{vm.value.firstValue != null ? vm.value.firstValue.toString() : @string/source1}"
This code displays @string/source1 upon first loading of a fragment before the vm.value completely being loaded by network call. Then, it display vm.value.firstValue when the network call succeeds. However, I want to display the @string/source1 only when network call fails.
I wonder if it is okay to display nothing(keep it empty) while waiting for the network call to be done successfully. then, populate TextView based on if a network call success or not. If this sounds okay, I would like to know how to acheive that using databinding.
The databinding framework cannot discern between a
nullvalue that is caused by the loading not being finished yet and anullvalue that is the result after loading. So you would have to implement such a discernment logic yourself.You could introduce a new
isLoadingboolean in your ViewModel. Whenever you trigger a loading operation, setisLoading=true, and after the loading is finished, setisLoading=false. Then use the following condition in your XML:You probably can further simplify the above statement like this:
For an explanation of the
??operator, see this StackOverflow question.If you don't want to create a new boolean variable in your ViewModel, you also can also initialize your
value.firstValuevariable to a default string that is displayed while loading:When loading the text fails, just set
And then use the following statement in your XML: