Spring BootでRxJava2を使う

Spring Boot 2はRxJava2をサポートしているので、Spring MVCとSpring WebFluxどちらでも、Controllerの戻り値にFlowableなどを指定できる。

ソースコード

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'io.reactivex.rxjava2:rxjava'
}
@RestController
public class HelloController {
    @GetMapping("/hello1")
    public Single<String> hello1() {
        return Single.just("Hello!");
    }

    @GetMapping("/hello2")
    public Flowable<String> hello2() {
        return Flowable.fromIterable(List.of("Hello!", "Hello!"));
    }

    @GetMapping(value = "/hello3", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flowable<String> hello3() {
        return Flowable.fromIterable(List.of("Hello!", "Hello!"));
    }
}

参考