Java.Reactive.What is the role of Subscription in reactive programming?

the Subscription plays a pivotal role in managing flow control and resource management in reactive programming.

Let’s break it down 👇


🎯 What is a Subscription?

In Reactive Streams (Java 9 Flow API, RxJava, Reactor, Akka Streams), a Subscription is the link between the Publisher (data producer) and the Subscriber (data consumer).

It gives the Subscriber control over:

  • How much data to receive (request(n))
  • When to stop receiving (cancel())

Think of it like a remote control 📺:
The subscriber can press “Give me more” or “Stop” at any time.

🧩 Core Responsibilities of Subscription

MethodPurpose
request(long n)Tells the Publisher: “I’m ready for n more items.” This enables backpressure.
cancel()Stops the data flow and unsubscribes the observer. Useful for cleanup and preventing memory leaks.

🧪 Example: Manual Control

import java.util.concurrent.Flow.*;

public class CustomReactiveFlow {
    public static void main(String[] args) {
        Publisher<Integer> publisher = subscriber -> {
            subscriber.onSubscribe(new Subscription() {
                int count = 0;
                boolean cancelled = false;

                @Override
                public void request(long n) {
                    for (int i = 0; i < n && !cancelled; i++) {
                        subscriber.onNext(count++);
                    }
                    subscriber.onComplete();
                }

                @Override
                public void cancel() {
                    cancelled = true;
                    System.out.println("Subscription cancelled");
                }
            });
        };

        Subscriber<Integer> subscriber = new Subscriber<>() {
            private Subscription subscription;

            @Override
            public void onSubscribe(Subscription s) {
                this.subscription = s;
                System.out.println("Subscribed");
                s.request(5); // ask for 5 items
            }

            @Override
            public void onNext(Integer item) {
                System.out.println("Received: " + item);
            }

            @Override
            public void onError(Throwable t) {}

            @Override
            public void onComplete() {
                System.out.println("Done");
            }
        };

        publisher.subscribe(subscriber);
    }
}

🧠 Why is Subscription So Important?

✅ Backpressure: Without request(n), fast publishers can overwhelm slow consumers.

✅ Laziness: Publishers don’t start emitting until request() is called — promotes efficiency.

✅ Cancellation: Prevents memory leaks and unnecessary computation.

✅ Resource management: Like closing files, sockets, or unsubscribing from events.

🔗 Where You See Subscription

LibraryRole of Subscription
Java Flow APIManual request() and cancel()
RxJavaAbstracted as Disposable
Project ReactorImplicit with BaseSubscriber, or accessed via .doOnSubscribe(...)
Spring WebFluxAutomatically handled — but still honors request(n) from clients
Akka StreamsBackpressure protocol handled under the hood via demand signaling

🧠 Why is Subscription So Important?

✅ Backpressure: Without request(n), fast publishers can overwhelm slow consumers.

✅ Laziness: Publishers don’t start emitting until request() is called — promotes efficiency.

✅ Cancellation: Prevents memory leaks and unnecessary computation.

✅ Resource management: Like closing files, sockets, or unsubscribing from events.


🔗 Where You See Subscription

LibraryRole of Subscription
Java Flow APIManual request() and cancel()
RxJavaAbstracted as Disposable
Project ReactorImplicit with BaseSubscriber, or accessed via .doOnSubscribe(...)
Spring WebFluxAutomatically handled — but still honors request(n) from clients
Akka StreamsBackpressure protocol handled under the hood via demand signaling
Posted in Без рубрики | Comments Off on Java.Reactive.What is the role of Subscription in reactive programming?

Java.Reactive.Tell me about RxJava, Project Reactor, Spring WebFlux, Akka Streams. Lets look at one simple example written on each of that libs with cold and hot subscription ?

Let’s compare RxJava, Project Reactor, Spring WebFlux, and Akka Streams, each with simple Cold vs Hot observable examples.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Reactive.Tell me about RxJava, Project Reactor, Spring WebFlux, Akka Streams. Lets look at one simple example written on each of that libs with cold and hot subscription ?

Java.Multithreading.What is java reactive flow ?

Java Reactive Flow, which is part of the Reactive Streams specification — the foundation of modern reactive libraries like RxJava, Project Reactor, and Akka Streams.


🌊 What is Java Reactive Flow?

✅ It’s a standard API introduced in Java 9 under:

java.util.concurrent.Flow

It defines a minimal and interoperable Reactive Streams system for asynchronous, non-blocking data streams with backpressure.

📦 Interfaces in java.util.concurrent.Flow:

public class Flow {
    public interface Publisher<T> { void subscribe(Subscriber<? super T> s); }
    public interface Subscriber<T> {
        void onSubscribe(Subscription s);
        void onNext(T item);
        void onError(Throwable t);
        void onComplete();
    }
    public interface Subscription { void request(long n); void cancel(); }
    public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {}
}

Let’s break them down 👇


🧩 Core Components

ComponentRole
PublisherEmits data (e.g. sensor, API, file read)
SubscriberReceives data
SubscriptionControls the flow: request(n) is how backpressure works
ProcessorBoth a subscriber and a publisher (useful for data transformation in between)

🔁 Example Lifecycle:

  1. Publisher calls subscribe() and gives the Subscriber a Subscription.
  2. Subscriber uses subscription.request(n) to say, “I’m ready for n items.”
  3. Publisher sends onNext() events up to n times.
  4. If done → calls onComplete()
    If error → calls onError(Throwable)

✅ Minimal Example:

import java.util.concurrent.Flow.*;

public class MyReactiveFlow {
    public static void main(String[] args) {
        Publisher<Integer> publisher = subscriber -> {
            subscriber.onSubscribe(new Subscription() {
                int count = 0;
                boolean canceled = false;

                @Override
                public void request(long n) {
                    for (int i = 0; i < n && !canceled; i++) {
                        subscriber.onNext(count++);
                    }
                    subscriber.onComplete();
                }

                @Override
                public void cancel() {
                    canceled = true;
                }
            });
        };

        Subscriber<Integer> subscriber = new Subscriber<>() {
            @Override
            public void onSubscribe(Subscription s) {
                System.out.println("Subscribed");
                s.request(5); // backpressure: I want 5 items
            }

            @Override
            public void onNext(Integer item) {
                System.out.println("Received: " + item);
            }

            @Override
            public void onError(Throwable t) {
                System.out.println("Error: " + t.getMessage());
            }

            @Override
            public void onComplete() {
                System.out.println("Completed");
            }
        };

        publisher.subscribe(subscriber);
    }
}

💡 Why Does This Matter?

  • Interoperability — Libraries like RxJava, Reactor, Akka Streams implement this spec.
  • Backpressure support — Ensures producers don’t overwhelm slow consumers.
  • Standards-based — Java developers can now write reactive systems with a shared model.

🛠 Libraries That Implement It:

LibraryNotes
RxJava 2/3Has Flowable, Publisher, and adapters
Project ReactorFlux, Mono extend Publisher
Spring WebFluxBuilt entirely on top of Reactive Streams
Akka StreamsFully compliant with the spec
Posted in Без рубрики | Comments Off on Java.Multithreading.What is java reactive flow ?

Java.Reactive.Explain the difference between Hot and Cold Observable

Understanding the difference between Hot and Cold Observables is crucial to mastering RxJava and reactive programming in general — especially when working with time-sensitive or shared data sources.

Let’s break it down clearly and visually 👇

❄️ Cold Observable

📌 What it is:

A Cold Observable doesn’t start emitting items until an observer subscribes.
Every subscriber gets its own independent sequence.

🔁 Think of it like:

A Netflix show — each person watches from the beginning when they hit “Play.”

🧪 Example:

Observable<Integer> cold = Observable.create(emitter -> {
    System.out.println("New subscription");
    emitter.onNext(1);
    emitter.onNext(2);
    emitter.onComplete();
});

cold.subscribe(i -> System.out.println("Subscriber 1: " + i));
cold.subscribe(i -> System.out.println("Subscriber 2: " + i));

✅ Output:

New subscription
Subscriber 1: 1
Subscriber 1: 2
New subscription
Subscriber 2: 1
Subscriber 2: 2

Each subscriber triggers a new emission from scratch.


🔥 Hot Observable

📌 What it is:

A Hot Observable starts emitting regardless of subscribers.
Subscribers only receive what is currently being emitted, not the full history.

🔁 Think of it like:

A live radio broadcast — tune in late, and you miss what’s already been played.

🧪 Example (RxJava + PublishSubject):

PublishSubject<String> hot = PublishSubject.create();

hot.subscribe(s -> System.out.println("Subscriber 1: " + s));

hot.onNext("One");
hot.onNext("Two");

hot.subscribe(s -> System.out.println("Subscriber 2: " + s));  // Joins late

hot.onNext("Three");

✅ Output:

Subscriber 1: One
Subscriber 1: Two
Subscriber 1: Three
Subscriber 2: Three
  • Subscriber 2 missed “One” and “Two” because it subscribed too late.
  • The stream is already “hot” and ongoing.

🔍 Summary Table

FeatureCold ObservableHot Observable
Emission TimingStarts on subscriptionStarts on creation or trigger
Per SubscriberIndependent streamsShared stream
Late SubscribersGet full sequence from startGet only current/live items
Use CaseAPIs, file reads, deferred opsUI events, sensor data, sockets
Rx TypesObservable, Single, FlowableSubject, ConnectableObservable, Shared Flow

🧠 Bonus: Making Cold Observable Hot

You can “heat up” a cold observable using .publish() and .connect():

Observable<Long> cold = Observable.interval(1, TimeUnit.SECONDS);
ConnectableObservable<Long> hot = cold.publish();
hot.connect(); // starts emitting

hot.subscribe(i -> System.out.println("Sub 1: " + i));

Thread.sleep(3000);

hot.subscribe(i -> System.out.println("Sub 2: " + i)); // joins late
Posted in Без рубрики | Comments Off on Java.Reactive.Explain the difference between Hot and Cold Observable

Java.Reactive.🎯 Who is the Consumer in Reactive Programming?

🧠 Summary

  • Backpressure = “Slow down! I can’t handle that much data right now!”
  • Prevents overwhelming the consumer.
  • Crucial for building robust, scalable, and memory-safe reactive systems.

In a reactive stream, the consumer is the Observer / Subscriber — the one who:

  • Subscribes to the stream (subscribe(...))
  • Processes each item received via onNext()
  • Might be slow due to I/O, computation, or limited resources

The producer emits data (the Observable, Flowable, Publisher)
The consumer receives and handles it (your code in .subscribe())

🧪 Example:

Flowable.range(1, 1_000_000)      // ✅ Producer (fast)
    .observeOn(Schedulers.io())   // Shift to background thread
    .map(i -> {
        Thread.sleep(5);          // ⏳ Simulate slow work
        return i;
    })
    .subscribe(i -> {
        System.out.println("Consumed: " + i);  // 👈 Consumer
    });

Here, the Flowable is the producer — it emits 1 to 1,000,000 as fast as possible.

The .subscribe() block is the consumer — it processes each item slowly.

This mismatch = potential for backpressure problems.

🧠 Visualization:

  [Producer: Fast Stream]
      ───────▶ 1
      ───────▶ 2
      ───────▶ 3
      ...
        |
        | (Backpressure boundary)
        ▼
  [Consumer: Slow Subscriber]
      ◼️ Process 1 (slow)
      ◼️ Process 2 (slow)

The consumer gets overwhelmed unless:

  • You apply a backpressure strategy,
  • Or control the flow with a request(n) mechanism (in Flowable or Publisher),
  • Or buffer/delay/drop excess data.

💬 How Can You Identify the Consumer?

It’s any code that calls:

.subscribe(item -> {
    // 👈 This is the consumer
});

Or, in a more verbose style:

Observer<Integer> observer = new Observer<>() {
    public void onNext(Integer item) {
        // 👈 This is the consumer
    }
};

In Spring WebFlux, it would be your controller method or a service that consumes a Flux or Mono.

🧰 In Reactive Streams Spec Terms

ComponentRole
PublisherProducer
SubscriberConsumer
SubscriptionMiddleman that allows request(n) (backpressure control)
Posted in Без рубрики | Comments Off on Java.Reactive.🎯 Who is the Consumer in Reactive Programming?

Java.Reactive.What is backpressure in the context of reactive programming?

🙌 Backpressure is one of the most important — and often misunderstood — concepts in reactive programming, especially when dealing with asynchronous streams.

Let’s unpack it clearly 👇

🔄 What is Backpressure?

Backpressure refers to a situation and a mechanism in reactive programming where:

🔹 The data producer is faster than the consumer,
🔹 So we need a way to slow down or buffer the data
🔹 Otherwise, we risk out-of-memory errors, dropped data, or crashes

🧠 Real-world Analogy:

Imagine you’re filling water into a cup:

  • If you pour too fast, the cup overflows.
  • The cup (consumer) needs a way to tell the faucet (producer) to slow down.

That’s backpressure.

🎯 Why Is It Important?

In reactive systems (like RxJava, Reactor, Spring WebFlux), you often deal with:

  • Fast publishers (e.g. user events, network messages, Kafka topics)
  • Slow consumers (e.g. writing to disk, slow database, UI rendering)

Without backpressure:

  • You may flood your system with more data than it can handle.
  • Memory usage spikes ⬆️, performance drops ⬇️, and bugs appear 🐛.

🛠 Reactive Types and Backpressure Support

TypeBackpressure?Notes
Observable❌ NoSuitable for UI or small, fast streams
Flowable✅ YesUse for high-throughput or unbounded streams
Publisher (Java Flow API)✅ YesPart of Reactive Streams specification
Mono / Flux (Project Reactor)✅ YesUsed in Spring WebFlux

🔄 How Flowable Handles Backpressure in RxJava

Flowable<Integer> fastSource = Flowable.range(1, 1000000)
    .observeOn(Schedulers.io());

fastSource
    .map(i -> {
        Thread.sleep(1); // simulate slow consumer
        return i;
    })
    .subscribe(System.out::println);

If you don’t handle backpressure, this may crash or behave unpredictably.

But with .onBackpressureBuffer():

fastSource
    .onBackpressureBuffer()
    .map(...)
    .subscribe(...);

You can choose what to do when pressure builds:

StrategyWhat It Does
onBackpressureBuffer()Buffers items until consumer is ready (default)
onBackpressureDrop()Drops new items if buffer is full
onBackpressureLatest()Keeps only the latest item, drops older ones
onBackpressureError()Throws an error immediately when overwhelmed

🔍 Spring WebFlux (Reactor)

Spring WebFlux’s Flux is backpressure-aware by default because it implements Publisher from the Reactive Streams spec.

Consumers can request(n) items — controlling how much they can handle.

🧠 Summary

  • Backpressure = “Slow down! I can’t handle that much data right now!”
  • Prevents overwhelming the consumer.
  • Crucial for building robust, scalable, and memory-safe reactive systems.
Posted in Без рубрики | Comments Off on Java.Reactive.What is backpressure in the context of reactive programming?

Java.Reactive.Describe the role of Observable and Observer in reactive programming

🎯 Goal of Reactive Programming:

To react to a stream of data/events over time, in a non-blocking, asynchronous, and declarative way.

This is achieved by two main players:


🧩 1. Observable<T> — The Data Source

✅ What it is:

An Observable is like a publisher or data stream. It emits:

  • Data (onNext)
  • Errors (onError)
  • Completion (onComplete)

You can think of it as a “smart pipe”:

  • You push data into it.
  • It knows how to process and send that data to whoever is listening.

🔧 Common ways to create an Observable:

Observable.just("A", "B", "C")  // Emits 3 items
Observable.fromIterable(list)   // Emits items from a list
Observable.create(...)          // Custom emission logic

🧩 2. Observer<T> — The Listener

✅ What it is:

An Observer is like a subscriber. It listens to the Observable, and reacts to:

  • New data (onNext(T t))
  • Errors (onError(Throwable e))
  • Completion (onComplete())

It’s like saying: “Hey, I’m interested in your updates — keep me posted!”

🔧 Example:

Observable<String> stream = Observable.just("A", "B", "C");

stream.subscribe(
    item -> System.out.println("Got: " + item),        // onNext
    error -> System.err.println("Error: " + error),    // onError
    () -> System.out.println("Completed")              // onComplete
);

📦 Together, they form a reactive flow:

[ Observable ] ──▶ onNext("A") ──▶ [ Observer ]
                ──▶ onNext("B")
                ──▶ onComplete()

Think of:

  • Observable = a stream of events
  • Observer = someone watching those events happen, and reacting

🧠 Real-world analogy:

ConceptAnalogy
ObservableA radio station broadcasting music
ObserverA radio listener tuned in

Once the station starts playing (emitting), everyone tuned in hears the songs (data), and if there’s a problem (error), the station may announce it or stop (complete).

🛠 Lifecycle Methods in Observer:

interface Observer<T> {
    void onSubscribe(Disposable d);  // (Optional) - when you subscribe
    void onNext(T value);            // When new data is emitted
    void onError(Throwable e);       // If something goes wrong
    void onComplete();               // When the stream finishes
}

But often, we just use the short subscribe(...) with lambdas.

🌀 Bonus: Hot vs Cold Observables

  • Cold: Starts emitting when someone subscribes (e.g. Observable.just()).
  • Hot: Already emitting whether you’re listening or not (e.g. mouse events).
Posted in Без рубрики | Comments Off on Java.Reactive.Describe the role of Observable and Observer in reactive programming

Java.Reactive.What is the Observer pattern and how does it underlie reactive programming?

The Observer Pattern is a behavioral design pattern where:

  • One object (the Subject) maintains a list of Observers.
  • When the Subject’s state changes, it notifies all its Observers.

Think of it like a subscription model:

  • You (Observer) subscribe to a newsletter (Subject).
  • When there’s a new issue, the newsletter sends it to all subscribers.
Continue reading →
Posted in Без рубрики | Comments Off on Java.Reactive.What is the Observer pattern and how does it underlie reactive programming?

Java.Reactive.How Many Threads Can You Have in RxJava?

📌 It depends on the Scheduler you use.


✅ Schedulers.io()

  • Purpose: For I/O-bound tasks like DB calls, file access, HTTP calls.
  • Type: Cached thread pool (like Java’s Executors.newCachedThreadPool()).
  • Threads: Unbounded (new threads created as needed, idle ones reused).
  • Good for: Many short, non-blocking, I/O operations.

⚠️ Careful! Too many blocking operations might spawn tons of threads and exhaust resources.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Reactive.How Many Threads Can You Have in RxJava?

Java.Reactive. observeOn(Schedulers.io()) — What does it really do?

This line changes the thread where the subscriber and everything downstream of it will run.


🔧 The Reactive Pipeline Has Stages

Imagine this code:

Observable.just("Stanley")
    .map(name -> name.toUpperCase())          // runs on thread A
    .observeOn(Schedulers.io())               // switch to thread B
    .subscribe(name -> System.out.println(name));  // runs on thread B

Here’s what happens:

  • just("Stanley") emits the data.
  • .map(...) transforms it (runs on the same thread as emission, usually main).
  • Then observeOn(Schedulers.io()) kicks in and switches the thread for everything after it.
  • So, subscribe(...) and anything below runs on an I/O thread, not the main one.

🔍 Real-life Analogy:

You’re cooking a meal:

  1. You chop veggies in the kitchen (main thread).
  2. Then you send them to a friend working in the garage (I/O thread) to fry them.
  3. They finish the dish and serve it.

So .observeOn(Schedulers.io()) is like changing the place (and worker) doing the rest of the work.

🤖 In Thread Terms:

If you add this inside each stage:

.map(data -> {
    System.out.println("Map on " + Thread.currentThread().getName());
    return data.toUpperCase();
})
.observeOn(Schedulers.io())
.subscribe(data -> {
    System.out.println("Subscribe on " + Thread.currentThread().getName());
});

You’d see output like:

Map on main
Subscribe on RxCachedThreadScheduler-1

🆚 .subscribeOn() vs .observeOn():

FunctionAffectsBehavior
subscribeOn()UpstreamControls where the Observable starts (data source, operators above)
observeOn()DownstreamSwitches thread for everything below it (where subscriber runs)

So if you want to move data generation and processing off the main thread, you can combine both:

Observable.just("Stanley")
    .subscribeOn(Schedulers.io())       // emission happens in I/O thread
    .observeOn(Schedulers.computation()) // processing happens in computation thread
    .map(...)
    .subscribe(...);
Posted in Без рубрики | Comments Off on Java.Reactive. observeOn(Schedulers.io()) — What does it really do?