RxJava有条件地从Single <string>或Maybe.empty()返回Maybe

时间:2019-05-14 01:18:04

标签: android rx-java rx-java2

我想使用Single作为返回类型,或者如果为null,则可能为空。

首先,我调用一个方法来获取布尔值:

Single<Boolean> isRemembered()

然后,如果此方法返回true,则调用此方法:

Single<String> getRemembered()

如果isRemembered()返回true,则getRemembered()永远不会为空值。

这是我在直播中的尝试:

public Maybe<String> getRememberIfExists(){
        return sharedPreferencesRepositoryType.isRemembered()
                .flatMapMaybe(aBoolean -> {
                    if(aBoolean){
                        return sharedPreferencesRepositoryType.getRemembered()
                                .flatMapMaybe(Maybe::just);
                    }else{
                        return Maybe.empty();
                    }
                });
    }

当isRemembered()返回true和false时,我都写了一个测试:

@Test
public void getRememberIfExists() {
    when(repository.getRemembered()).thenReturn(Single.just(REMEMBERED));
    when(repository.isRemembered()).thenReturn(Single.just(true));

    TestObserver<String> observer = interactor.getRememberIfExists()
            .test();

    verify(repository).isRemembered();
    verify(repository).getRemembered();

    observer.assertNoErrors()
            .assertComplete()
            .assertValueCount(1);

    assertEquals(REMEMBERED, observer.values().get(0));


}

@Test
public void getRememberIfExistsError(){
    when(repository.isRemembered()).thenReturn(Single.just(false));

    TestObserver<String> testObserver = interactor.getRememberIfExists()
            .test();

    verify(repository).isRemembered();

    testObserver.assertComplete();
    testObserver.assertEmpty();

}

第一次测试成功。第二个失败:

java.lang.AssertionError: Completed! (latch = 0, values = 0, errors = 0, completions = 1)

在:

testObserver.assertEmpty()

关于如何正确编写上述getRememberIfExists()方法的任何建议?

1 个答案:

答案 0 :(得分:2)

根据reference doc assertEmpty

  

返回一个(单个)Maybe实例,该实例立即调用onComplete。

因此,请使用“ assertNoValues”代替“ assertEmpty”:

@Test
public void getRememberIfExistsError(){
    when(repository.isRemembered()).thenReturn(Single.just(false));

    TestObserver<String> testObserver = interactor.getRememberIfExists()
            .test();

    verify(repository).isRemembered();

    testObserver.assertComplete();
    testObserver.assertNoValues()

}