Last active
December 14, 2015 08:19
-
-
Save dlhartveld/5057313 to your computer and use it in GitHub Desktop.
Implementation of an Observable with data stream methods, similar in its idea to .NET's reactive extensions. Note: this example only demonstrates the expressive power of Java 8's functional types, default methods and lambda expressions - it does not demonstrate a pattern that should be used in general.
This file contains hidden or 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
package com.hartveld.examples; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
public interface Observable<T> { | |
void subscribe(Consumer<T> onNext); | |
default <R> Observable<R> map(Function<T, R> mapper) { | |
return onNext -> { | |
subscribe(e -> { | |
onNext.accept(mapper.apply(e)); | |
}); | |
}; | |
} | |
default Observable<T> filter(Predicate<T> filter) { | |
return onNext -> { | |
subscribe(e -> { | |
if (filter.test(e)) { | |
onNext.accept(e); | |
} | |
}); | |
}; | |
} | |
default <R> Observable<R> bind(Function<T, Observable<R>> binder) { | |
return onNext -> { | |
subscribe(e -> { | |
binder.apply(e).subscribe(onNext); | |
}); | |
}; | |
} | |
// Alternative filter implementation based on bind. | |
default Observable<T> filter2(Predicate<T> filter) { | |
return bind(t -> { | |
return onNext -> { | |
if (filter.test(t)) { | |
onNext.accept(t); | |
} | |
}; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment