Tomáš Zato
Tomáš Zato

Reputation: 53267

Does Java have an equiavalent to boost's or Qt's signals?

The features mentioned in title serve a simple purpose: allow an user to bind some event listeners to an object which will dispatch all event listeners when event occurs.

This simple concept can, of course, achieved like this:

public class EventEmitter extends ArrayList<Runnable>;

But I would prefer a smarter emitter - ideally one that allows arguments to be passed to the callback. Runnable does not have any arguments of course. Lambda expressions do have parameters on the other side.

Smart emitters allow you to define specific callback parameters:

EventEmitter<String, Boolean> emitter = new EventEmitter();

My question whether this thing is part of java library or if I have to implement it myself. On google, I only found some java.awt.AWTEvent but that is not event dispatcher.

My preferred pseudo code:

// Requires lambdas with (File, int) signature
public final EventEmitter<File, int> downloadCompleteEvent;

And new events added as:

downloaderClass.downloadCompleteEvent
   .addListener(
       (File file, int downloadTime)->System.out.println("Downloaded "+file.getAbsolutePath()+" in "+downloadTime+" seconds.")
   );

And dispatch events as:

this.downloadCompleteEvent.dispatch(downloadedFile, elapsedTime);

Upvotes: 0

Views: 1102

Answers (2)

Prim
Prim

Reputation: 2978

In pure Java, you can use a CompletableFuture which represents a state or a work currently in action. On a completable future, you can add one or more listeners which will be invoked with result.

by example:

public CompletableFuture<DownloadResult> download() {
    // computing a result async
    CompletableFuture<DownloadResult> future = CompletableFuture.supplyAsync(/* your process*/);
    return future;
}

future.thenAccept( (DownloadResult) r -> { ... } ); 
// will be called when process is done

Also, you can be interested by EventBus into Guava library: https://github.com/google/guava/wiki/EventBusExplained

Or by RXJava library: https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava

Upvotes: 1

Josh Kitchens
Josh Kitchens

Reputation: 1110

Some libraries may have a class that can be extended to add this functionality, but it is not a native java idiom. If you want this functionality you need to track and notify event listeners yourself via the observer pattern.

Upvotes: 0

Related Questions