在 RxJava2 中处理 null [英] Handle null in RxJava2

查看:38
本文介绍了在 RxJava2 中处理 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从本地或远程加载数据.如果获取本地数据,则不会获取远程数据.

There is a need where I want load data from local or remote. If local data fetched, remote data won't be fetched.

由于本地数据可以为空(即空),我必须在 RxJava2 中处理 null 的情况,所以我在 Optional util.这是代码.

As local data can be empty (i.e. null), I have to handle null situation in RxJava2, so I do it with help of Optional util in java-8. Here is code.

String data;

Observable<Optional<String>> loadCacheData() {
    return Observable.create(emitter -> {
        emitter.onNext(Optional.ofNullable(null));
        emitter.onComplete();
    });
}

Observable<Optional<String>> loadRemoteData() {
    Observable<Optional<String>> remoteObservable = Observable.create((ObservableOnSubscribe<Optional<String>>) emitter -> {
        Thread.sleep(2000);
        emitter.onNext(Optional.of("FromRemote"));
        emitter.onComplete();
    }).subscribeOn(Schedulers.io());

    remoteObservable.doOnNext(s -> data = s.get());

    return remoteObservable;
}

void fetchData() {
    Observable.concat(loadCacheData(), loadRemoteData())
            .filter(s -> s.isPresent())
            .firstElement()
            .subscribe(s -> System.out.println(s.get()));
}

我想知道在这种情况下有没有其他方法可以处理 null.

I want to know is there any other way to handle null in such situation.

推荐答案

看起来你想要做的正是 也许 提供:一个可以有也可以没有数据的来源.

It seems like what you are trying to do is exactly what Maybe provides: a source that can either have or not have data.

以下是我如何看待此工作的示例:

Here's an example of how I see this working:

public class MaybeExample {

    private final Network network;

    private String cachedData;

    public MaybeExample(final MaybeNetwork network) {
        this.network = network;
    }

    // Just used for the test... you'll probably have something smarter
    public void setCachedData(final String data) {
        cachedData = data;
    }

    private Maybe<String> loadCacheData() {
        return cachedData != null ? Maybe.just(cachedData) : Maybe.empty();
    }

    private Single<String> loadRemoteData() {
        return network.getData();
    }

    public Single<String> fetchData() {
        return loadCacheData().switchIfEmpty(loadRemoteData());
    }
}

这将是一个测试,看看它的实际效果:

And this would be a test to see it in action:

public class MaybeExampleTest {

    @Mock
    private Network network;

    private MaybeExample maybeExample;

    @Before
    public void createExample() {
        MockitoAnnotations.initMocks(this);
        maybeExample = new MaybeExample(network);
    }

    @Test
    public void nullCachedDataReturnsNetworkData() {
        maybeExample.setCachedData(null);
        final String networkValue = "FromNetwork";
        when(network.getData()).thenReturn(Single.just(networkValue));

        final TestObserver<String> observer = maybeExample.fetchData().test();

        observer.assertValue(networkValue);
    }

    @Test
    public void cachedDataIsReturnedWithoutCallingNetwork() {
        final String cachedValue = "FromCache";
        maybeExample.setCachedData(cachedValue);
        when(network.getData()).thenReturn(Single.error(new UnsupportedOperationException()));

        final TestObserver<String> observer = maybeExample.fetchData().test();

        observer.assertValue(cachedValue);
        observer.assertNoErrors();
    }
}

这篇关于在 RxJava2 中处理 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆