如何在不调用 observe() 的情况下从映射的 LiveData 的 getValue() 获得非空结果?

How to get non null result from getValue() of mapped LiveData without calling observe()?

我正在使用 Transformations.map 方法在原始方法的基础上得到一个新的 LiveData。虽然 getValue 方法的原始 returns 始终是正确的值,但映射到 returns null 的访问器相同。

如何解决或变通解决此问题,以便在不调用 observe 的情况下测试 class 公开 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必须先观察

待编辑 post:在尝试获取映射值之前,只需调用 mapped.observeForever(); 传入空观察器。