When do you use map
vs flatMap
in RxJava?
Say, for example, we want to map Files containing JSON into Strings that contain the JSON–
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 :(
}
});
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);
}
}
});
}
});
I like the simplicity of the 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.
Best Answer
map
transform one event to another.flatMap
transform one event to zero or more event. (this is taken from IntroToRx)As you want to transform your json to an object, using map should be enough.
Dealing with the FileNotFoundException is another problem (using map or flatmap wouldn't solve this issue).
To solve your Exception problem, just throw it with a Non checked exception : RX will call the onError handler for you.
the exact same version with flatmap :
You can return too, in the flatMap version a new Observable that is just an error.