Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does .defer() do in RxJava?

Tags:

rx-java

I am new to rx java and I cannot understand what Completable.defer brings and why it's a good practice to use it.

so, what's the difference between:

public Completable someMethod1() {
    return Completable.defer(() -> someMethod2());
}

vs

public Completable someMethod1() {
    return someMethod2();
}

I can see that in the method's implementation there is some exception handling but this is surpassing me. Appreciate it.

like image 512
aurelius Avatar asked Dec 03 '22 10:12

aurelius


1 Answers

Defer will makes sure each subscriber can get its own source sequence, independent of the other subscribers. Let me illustrate it with two examples:

AtomicInteger index = new AtomicInteger();

Flowable<String> source =
    Flowable.just("a", "b", "c", "d", "e", "f")
    .map(v -> index.incrementAndGet() + "-" + v)
    ;

source.subscribe(System.out:println);

source.subscribe(System.out:println);

prints

1-a
2-b
3-c
4-d
5-e
6-f
7-a
8-b
9-c
10-d
11-e
12-f

versus

Flowable<String> source =
    Flowable.defer(() -> {
        AtomicInteger index = new AtomicInteger();

        return Flowable.just("a", "b", "c", "d", "e", "f")
               .map(v -> index.incrementAndGet() + "-" + v)
               ;
    })
    ;

source.subscribe(System.out:println);

source.subscribe(System.out:println);

prints

1-a
2-b
3-c
4-d
5-e
6-f
1-a
2-b
3-c
4-d
5-e
6-f

In the second example, there is a per subscriber state that would have been otherwise shared across all subscribers. Now since each subscriber gets its own individual sequence created, both index items as one would generally expect.

like image 123
akarnokd Avatar answered Feb 25 '23 20:02

akarnokd