(Quick Reference) # 11.2 Reactive Programming with RxJava Version: 3.2.7 ## Table of Contents ## 11.2 Reactive Programming with RxJava Since Grails 3.2, you can use RxJava to write reactive logic in your Grails controllers that leverages the underlying containers asynchronous processing capabilities. To get started simply declare a dependency on the plugin in `build.gradle`: build.gradle
    dependencies {
        ...
        compile 'org.grails.plugins:rxjava'
    }
You can then return `rx.Observable` as a return value from any controller and Grails will automatically apply the following steps: Create a new asynchronous request Spawn a new thread that subscribes to the observable When the observable omits a result process the result using the respond method. For more detailed instructions on how to use the RxJava plugin see the user guide documentation for the plugin. ## 11.2.1 Server Sent Events Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C. The RxJava plugin adds support for SSE to Grails making it simple to write controllers that maintain continuous non-blocking communication with a JavaScript client. For example:
    def index() {

        rx.stream { Subscriber subscriber -> (1)
           for(i in (0..5)) {
               if(i % 2 == 0) {
                   subscriber.onNext(
                       rx.render("Tick") (2)
                   )
               }
               else {
                   subscriber.onNext(
                       rx.render("Tock")
                   )

               }
               sleep 1000 (3)
           }
           subscriber.onCompleted() (4)
       }
    }
1 | Call the `stream` method passing a closure that accepts an `rx.Subscriber` to start sending events
2 | Emit a one or many items using `onNext`
3 | Call `sleep` to simulate a slow request
4 | Call `onCompleted` to complete the request
For more detailed instructions on how to use SSE and the RxJava plugin see the user guide documentation for the plugin. ## 11.2.2 RxGORM RxGORM is new implementation of GORM that has the following goals: Reactive Non-blocking Stateless Simple RxGORM, unlike the Asynchronous GORM implementation, aims to be truly non-blocking, down to the driver level. The following is an example of RxGORM in action:
    Book.get(id)
        .subscribe { Book it ->
        println "Title = ${it.title}"
    }
You can combine RxGORM with the RxJava plugin to implement reactive responses from Grails controllers. For example:
    def show() {
            // returns an rx.Observable
        Book.get(params.id?.toString())
    }
For more information on how to use RxGORM, see the RxGORM user guide. | Quick Reference (hide)