tags:

views:

202

answers:

2

Is there any equivalent of Reactive Extensions (.NET) for Java?

About Rx (Reactive Extensions)

Rx is a library for composing asynchronous and event-based programs using observable collections.

I am aware of rule engines such as Drools from JBOSS, but is there some other way that is closer to the Microsoft .NET approach?

+4  A: 

I'm not aware of one - and frankly it would be hard to do in such a neat fashion. The threading side is fine; Java's perfectly capable when it comes to threading... but at the moment, the language just doesn't support the appropriate features.

One of the neat design features of LINQ is that everything is based on interfaces and then extension methods are used to add extra functionality. That allows code to read fluently - imagine if you had to write:

IObservable<int> = Observable.Select(
                       Observable.Where(
                           source, x => x.SomeCondition)
                       x => x.SomeProjection);

Ick. The extension method is much more graceful:

IObservable<int> = source.Where(x => x.SomeCondition)
                         .Select(x => x.SomeProjection);

Now a Java version could be based on an abstract base class instead, but that would lose some of the elegance.

Next come lambda expressions and method group conversions - these really are fundamental to LINQ in general; the closest equivalent in Java (anonymous inner classes) are too ugly to be used everywhere you'd use a lambda expression in C#.

Basically, a Java version of Rx would be feasible, but it wouldn't be nearly as elegant as the C# version - which is probably why it hasn't been done as far as I'm aware. There may be other "asynchrony-driven" libraries around for Java, but they're unlikely to be as comprehensive and neat as Rx.

It's possible that the changes in Java 7 will make this more feasible; as far as I know extension methods aren't being introduced, but an abstract base class version would be reasonable if the lambda syntax ends up being okay...

Jon Skeet
Ok, thanks. Maybe this is more feasible in Java 7 with closures.
Timo Westkämper
+1  A: 

You might consider porting RxAs (wiki), written in ActionScript 3, to Java 7 when it arrives. The project (my own) is opensource and includes black-box unit tests of the .NET version of the framework to ensure compatibility.

Like Java, AS3 supports neither extension methods nor lambda expressions so the implementation may be similar. Having said that, you would need to be careful with race conditions since the AVM doesn't support threads so there is no locking code in RxAs.

Richard Szalay
@richard-szalay, thanks for the pointer.
Timo Westkämper