Search code examples
java.netlinqsystem.reactive

Reactive Extensions for Java


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?


Solution

  • 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...