HowTo: Reactive Stream with Spring Boot and RxJava in Kotlin

https://camo.githubusercontent.com/715acdfbaba13dbfad01b66fc4acd389d2c2344d/68747470733a2f2f6d656469612e67697068792e636f6d2f6d656469612f6368754e76306e45645544596e614c6e39392f67697068792e676966

Lets start

data class Car(val name: String, val model: String, val company: String)
fun getDataStream() : Observable<Car> {
val publishSubject = PublishSubject.create<Car>()
GlobalScope.async {
Thread.sleep(100)
emitRandomCarsWithTimeout(publishSubject)
}
return
publishSubject
}

fun emitRandomCarsWithTimeout(publishSubject: PublishSubject<Car>) {
for (i in 0..10) {
Thread.sleep(150)
publishSubject.onNext(createRandomCar())
}
publishSubject.onComplete()
}
@Controller
class RestEndpoint {

@Autowired
lateinit var dataProvider: DataProvider

@GetMapping(path = ["cars"], produces = [MediaType.APPLICATION_STREAM_JSON_VALUE])
@ResponseBody
@ApiResponses(value = [ApiResponse(code = 200, message = "Cars")])
fun getCarsAsStream(): Observable<Car> {
return dataProvider.getDataStream()
}

@GetMapping(path = ["cars"], produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
@CrossOrigin(origins = ["http://localhost:8081"])
fun getCarsAsJson(): List<Car> {
return dataProvider.getDataStream().toList().blockingGet()
}

}

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store