你什么时候在RxJava中使用map vs flatMap? [英] When do you use map vs flatMap in RxJava?

查看:185
本文介绍了你什么时候在RxJava中使用map vs flatMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你什么时候在RxJava中使用map vs flatMap?

When do you use map vs flatMap in RxJava?

比如说,我们想把包含JSON的文件映射到包含JSON的字符串 -

Say for example, we want to map Files containing JSON into Strings that contain the JSON--

使用map,我们必须以某种方式处理异常。但是如何?:

Using map, we have to deal with the Exception somehow. But how?:

Observable.from(jsonFile).map(new Func1<File, String>() {
    @Override public String call(File file) {
        try {
            return new Gson().toJson(new FileReader(file), Object.class);
        } catch (FileNotFoundException e) {
            // So Exception. What to do ?
        }
        return null; // Not good :(
    }
});

使用flatMap,它更加冗长,但我们可以将问题转发到Observables链中并在我们选择的地方处理错误否则甚至重试:

Using flatMap, it's much more verbose, but we can forward the problem down the chain of Observables and handle the error if we choose somewhere else and even retry:

Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
    @Override public Observable<String> call(final File file) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override public void call(Subscriber<? super String> subscriber) {
                try {
                    String json = new Gson().toJson(new FileReader(file), Object.class);

                    subscriber.onNext(json);
                    subscriber.onCompleted();
                } catch (FileNotFoundException e) {
                    subscriber.onError(e);
                }
            }
        });
    }
});

我喜欢地图的简单性,但是flatmap的错误处理(不是详细程度)。我没有看到任何有关此问题的最佳实践,我很好奇这是如何在实践中使用的。

I like the simplicity of map, but the error handling of flatmap (not the verbosity). I haven't seen any best practices on this floating around and I'm curious how this is being used in practice.

推荐答案

map 将一个事件转换为另一个事件。
flatMap 将一个事件转换为零个或多个事件。 (这取自 IntroToRx

map transform one event to another. flatMap transform one event to zero or more event. (this is taken from IntroToRx)

由于你想将json转换为一个对象,使用map应该足够了。

As you want to transform your json to an object, using map should be enough.

处理FileNotFoundException是另一个问题(使用map或flatmap)不会解决这个问题。)

Dealing with the FileNotFoundException is another problem (using map or flatmap wouldn't solve this issue).

要解决您的异常问题,只需将其抛出非检查异常:RX将为您调用onError处理程序。

To solve your Exception problem, just throw it with a Non checked exception : RX will call the onError handler for you.

Observable.from(jsonFile).map(new Func1<File, String>() {
    @Override public String call(File file) {
        try {
            return new Gson().toJson(new FileReader(file), Object.class);
        } catch (FileNotFoundException e) {
            // this exception is a part of rx-java
            throw OnErrorThrowable.addValueAsLastCause(e, file);
        }
    }
});

与flatmap完全相同的版本:

the exact same version with flatmap :

Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
    @Override public Observable<String> call(File file) {
        try {
            return Observable.just(new Gson().toJson(new FileReader(file), Object.class));
        } catch (FileNotFoundException e) {
            // this static method is a part of rx-java. It will return an exception which is associated to the value.
            throw OnErrorThrowable.addValueAsLastCause(e, file);
            // alternatively, you can return Obersable.empty(); instead of throwing exception
        }
    }
});

你也可以在flatMap版本中返回一个新的Observable,这只是一个错误。

You can return too, in the flatMap version a new Observable that is just an error.

Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
    @Override public Observable<String> call(File file) {
        try {
            return Observable.just(new Gson().toJson(new FileReader(file), Object.class));
        } catch (FileNotFoundException e) {
            return Observable.error(OnErrorThrowable.addValueAsLastCause(e, file));
        }
    }
});

这篇关于你什么时候在RxJava中使用map vs flatMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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