> Markdown version of [Reactive Services](https://vaadin.com/docs/next/flow/react-views/browser-callable-services/reactive-services). Section index: [llms.txt](https://vaadin.com/docs/next/flow/llms.txt)

# Reactive Services

A method of a browser-callable service can return a stream of values instead of a single value. The view then gets each value when the server emits it, until the stream ends or the view cancels its subscription.

## <a id="server-side"></a>Server Side

A reactive method returns a [Reactor](https://projectreactor.io/) `Flux`, or an `EndpointSubscription` that wraps one. Other reactive types aren’t supported. Convert a `Mono` to a `Flux` with its `flux()` method.

The access annotations and the [parameter validation](https://vaadin.com/docs/next/flow/react-views/browser-callable-services.md#validation) apply when the browser subscribes. When access is denied, the subscription ends with an error. When the arguments fail validation, the server logs the exception, but the subscription gets neither values nor an error.

`EndpointSubscription` adds a callback that runs when the browser cancels the subscription, or when the browser loses its connection to the server. The callback doesn’t run when the `Flux` completes or fails. Create the subscription with `EndpointSubscription.of()`:

`ReactiveService.java`

```java
@AnonymousAllowed
public Flux<@NonNull String> getClock() {
    return Flux.interval(Duration.ofSeconds(1)).onBackpressureDrop()
            .map(_interval -> new Date().toString());
}

@AnonymousAllowed
public EndpointSubscription<@NonNull String> getClockCancellable() {
    return EndpointSubscription.of(getClock(), () -> {
        LOGGER.info("Subscription has been cancelled");
    });
}
```

## <a id="browser-side"></a>Browser Side

The generated function of a reactive method returns a `Subscription` right away, instead of a `Promise`. It has no [request options](https://vaadin.com/docs/next/flow/react-views/browser-callable-services.md#request-options). The values come through a push connection, which all the subscriptions of the page share.

The methods of a `Subscription` register callbacks and return the subscription, so that the calls can be chained:

- `onNext(callback)`

  Called with each value.

- `onError(callback)`

  Called with a message when the stream fails. No values follow. When the `Flux` fails, the message is `Exception in Flux`, and the server logs the exception.

- `onComplete(callback)`

  Called when the stream ends. No values follow.

- `cancel()`

  Ends the subscription. No values follow. Cancel subscriptions to streams that don’t end on their own, for example when the component that shows the values is removed.

- `onConnectionStateChange(callback)`

  Called with an event when the state of the subscription changes. Its `detail.state` is `connecting`, `connected`, or `closed`.

- `onSubscriptionLost(callback)`

  Called when the connection to the server is restored, but the subscription is no longer valid. The callback returns what to do: `ActionOnLostSubscription.RESUBSCRIBE` subscribes to the method again, and `ActionOnLostSubscription.REMOVE` forgets the subscription. Without a callback, or when it returns nothing, the client forgets the subscription.

- `context(host)`

  Cancels the subscription when the given Lit element is removed from the page. React views cancel the subscription in the cleanup function of an effect instead.

The following view shows the values of the clock service above, and cancels the subscription when the view is removed:

```tsx
import { ActionOnLostSubscription } from '@vaadin/hilla-frontend';
import { useEffect, useState } from 'react';
import { ReactiveService } from 'Frontend/generated/endpoints';

export default function ClockView() {
  const [time, setTime] = useState('');

  useEffect(() => {
    const subscription = ReactiveService.getClockCancellable()
      .onNext(setTime)
      .onSubscriptionLost(() => ActionOnLostSubscription.RESUBSCRIBE);
    return () => subscription.cancel();
  }, []);

  return <p>Server time: {time}</p>;
}
```
