Skip to content

Spying on events#

Spies are useful when you need to track which events flow into a Uni or a Multi. Spies can track events from groups such as onItem(), onFailure(), onSubscribe(), etc.

The io.smallrye.mutiny.helpers.spies.Spy interface offers factory methods to spy on selected groups, or even on all groups.

Spying selected groups#

The following example spies on requests and completion group events:

1
2
3
4
5
6
7
8
Multi<Integer> multi = Multi.createFrom().items(1, 2, 3);
MultiOnRequestSpy<Integer> requestSpy = Spy.onRequest(multi);
MultiOnCompletionSpy<Integer> completionSpy = Spy.onCompletion(requestSpy);

completionSpy.subscribe().with(System.out::println);

System.out.println("Number of requests: " + requestSpy.requestedCount());
System.out.println("Completed? " + completionSpy.invoked());

The standard output stream shall display the following text:

1
2
3
Number of requests: 9223372036854775807
Completed? true

The number of requests corresponds to Long.MAX_VALUE, and a completion event was sent.

Important

It is important to note that spies observe and report events for all subscribers, not just one in particular.

You should call the .reset() method on a given spy to resets its statistics such as the invocation count.

Spying all groups#

You can take advantage of a global spy if you are interested in all event groups:

1
2
3
4
5
6
7
8
9
Multi<Integer> multi = Multi.createFrom().items(1, 2, 3);
MultiGlobalSpy<Integer> spy = Spy.globally(multi);

spy.subscribe().with(System.out::println);

System.out.println("Number of requests: " + spy.onRequestSpy().requestedCount());
System.out.println("Cancelled? " + spy.onCancellationSpy().isCancelled());
System.out.println("Failure? " + spy.onFailureSpy().lastFailure());
System.out.println("Items: " + spy.onItemSpy().items());

Running the snippet above gives the following output:

1
2
3
Number of requests: 9223372036854775807
Cancelled? false
Failure? null
Items: [1, 2, 3]

Warning

Tracking onItem() events on a Multi requires storing all items into a list, which can yield an out-of-memory exception with large streams.

In such cases consider using Spy.onItem(multi, false) to obtain a spy that does not store items, but that can still report data such as the number of received events (see spy.invocationCount()).