Observable using defer

Kumar Pallav's photo
Kumar Pallav

Published on Jan 22, 2020

1 min read

Subscribe to my newsletter and never miss my upcoming articles

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

Share this