Last active
July 12, 2018 19:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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