Skip to content

Instantly share code, notes, and snippets.

@falemagn
Last active July 12, 2018 19:52
Show Gist options
  • Save falemagn/7bc9168722f19702b5d133374734eb58 to your computer and use it in GitHub Desktop.
Save falemagn/7bc9168722f19702b5d133374734eb58 to your computer and use it in GitHub Desktop.
[RxJava 2] Transformer that implements a map that ignores nulls and continues processing the observable output
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;
import java.util.Optional;
public class MapIgnoreNulls {
public static <T,R> ObservableTransformer<T,R> create(Function<? super T, ? extends R> mapper) {
return observable -> observable
.map(t -> Optional.ofNullable(mapper.apply(t)))
.filter(Optional::isPresent)
.map(Optional::get);
};
}
/*
* Use it like this:
*
* Observable.[...].compose(MapIgnoreNulls::create(v -> {
* // Your mapping code that can potentially map v to null.
* // If the mapped value is null, then the value is ignored and processing continues
* }))
*
* /
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment