我正在使用 Transformations.map
方法来获取基于原始数据的新 LiveData
。虽然原始的 getValue
方法始终返回正确的值,但映射的相同访问器返回 null
。
如何解决或解决此问题,以便在不调用 observe
的情况下测试公开 LiveData
的类?
下面是解释这个问题的代码:
public class LiveDataTest {
@Rule
public TestRule rule = new InstantTaskExecutorRule();
@Test
public void mapTest() {
final MutableLiveData<String> original = new MutableLiveData<>();
final LiveData<String> mapped = Transformations.map(original, input -> "Mapped: " + input);
System.out.println(original.getValue()); // null - OK
System.out.println(mapped.getValue()); // null - OK
original.setValue("Hello, World!");
System.out.println(original.getValue()); // "Hello, World!" - OK
System.out.println(mapped.getValue()); // null - Should be "Mapped: Hello, World!"
}
}
最佳答案
来自文档 https://developer.android.com/reference/android/arch/lifecycle/Transformations :
The transformations aren't calculated unless an observer is observing the returned LiveData object.
所以必须首先观察到mapped
。
要编辑帖子:只需调用 mapped.observeForever();
传入空观察器,然后再尝试获取映射值。
关于android - 如何在不调用 observe() 的情况下从映射的 LiveData 的 getValue() 获得非空结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52004118/