Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ass.excercises.cvi8.snippets;
- import io.reactivex.Observable;
- public class CommonMistakeExample {
- public static void main(String[] args) {
- System.out.println("===== Wrong =====");
- wrong();
- System.out.println("===== Correct =====");
- correct();
- /* Outputs:
- * ===== Wrong =====
- Done work in source1
- Done work in source2
- For each: 'source1'
- ===== Correct =====
- Done work in source1
- For each: 'source1'
- */
- }
- private static void wrong() {
- Observable.concat(
- sourceWrong(1),
- sourceWrong(2)
- )
- .first("N/A")
- .toObservable()
- .forEach(s -> System.out.printf("For each: '%s'\n", s));
- }
- private static Observable<String> sourceWrong(int num) {
- // This is a wrong approach!
- // first be do some work
- doWork();
- System.out.println("Done work in source"+num);
- String resultOfWork = "source"+num;
- // then we create observable that already has it's content ready
- return Observable.just(resultOfWork);
- }
- private static void correct() {
- Observable.concat(
- sourceCorrect(1)
- .doOnNext(s -> System.out.println("Note that this is a correct way to log activity of Observable")),
- sourceCorrect(2)
- )
- .first("N/A")
- .toObservable()
- .forEach(s -> System.out.printf("For each: '%s'\n", s));
- }
- private static Observable<String> sourceCorrect(int num) {
- // this illustrates very simple way of fixing the problem:
- // defer work to later: deferred code will be called only when someone
- // will subscribe on Observable and with concat+first combination,
- // it will occur only when first Observable in concat will return empty Observable;
- return Observable.defer(() -> {
- doWork();
- System.out.println("Done work in source"+num);
- String resultOfWork = "source"+num;
- return Observable.just(resultOfWork);
- });
- }
- private static void doWork() {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement