Skip to main content

Command Palette

Search for a command to run...

Observable using defer

Published
1 min read

Observable normally gets created once the code executes, Observable using defer , defers the creation of Observable. It waits till a subscription is done.

Below are main property of Observable using defer.

  1. Creates new observable every time on subscription
  2. No Observable is created until subscription

Below is the code showing Observable using defer

package com.codingsaint.learning.rxjava.observables;

import com.codingsaint.learning.rxjava.observer.DemoObserver;
import com.codingsaint.learning.rxjava.utils.RxUtils;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ObservableUsingDefer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ObservableUsingDefer.class);

    public static void main(String... args) {
        Observable<Integer> observableUsingDefer = Observable.defer(() -> {
            return Observable.fromIterable(RxUtils.postiveNumbers(5));
        });
        observableUsingDefer.subscribe(new DemoObserver());
        observableUsingDefer.subscribe(new DemoObserver());


    }
}

Here intentionally we are subscribing 2 times to show that each time Observable is created. You can also see that defer is taking fromIterable to create the observable. This will stop creating defer until we subscribe. Once subscribed Observable.fromInterable code will be invoked

34 views

More from this blog

C

Coding Saint - Simple Short Tutorials

52 posts

I am Kumar Pallav, a passionate programmer.I love java, open source & microservices . I create Simple , Short Tutorials Follow me at https://twitter.com/kumar_pallav