Reactive Programming by Example: Intro to Pivotal Reactor
Speaker: Victor Grazi @vgrazi
https://github.com/vgrazi/reactive-demo
See list of all bog posts from conference
What is Reactive
- Think in streams – but more powerful than Java 8 streams
- reactive streams – high performance, async stream processing non-blocking back pressure – when ready to stop getting data
- declarative
- doesn’t vary much by language
Maven dependencies
- reactor-core
- reactor-test – ex: simulate waiting X seconds without actually waiting
Everything is a stream of messages – ex: events, query results, exceptions (errors aren’t special; still a message)
Publisher – Flux emits event messages (Observable in rx-java), immutable
Subscriber – gets next message and handles events on error/complete/subscribe. doOnNext() is like peek() in Java 8 for debugging
Marble diagram
- treat events as marbles
- Website: http://rxmarbles.com – can see different operations and drag marbles (on a computer; doesn’t work on iPad)
Creating a flux
Flux.just(singleValue)
Flux.fromIterable/fromArray – to transform from collection/array
Flux.range(startNumber, numberOfElementsInRange)
Flux.interval(Duration.ofSeconds(n)) – emit a value every X seconds
Flux.merge – combine streams
Flux.withLatestFrom – unlike zip, get latest available element rather than getting the “next” one
Flux.create – use lambda to create a listener with logic for publishing elements
Transformations
take
skip
distinct
distinctUntilChanged-only eliminate adjacent duplicates
filter
map
flatMap
zipWith – combine existing stream with another stream in tuples
sort
Differences from Java streams
- push based,not pull based
- Attached to real time feeds
- Conncurrent
- Back pressure
- Can only use once
- Can compose streams (zip/merge)
- Can fully work with infinite streams
Cold vs Hot Flux
Cold streams are finite, known elements. Hot streams are more realistics
Must call subscribe for anything to happen (like a terminal operator in Java 8 streams)
I learned a lot. Or reviewed a lot and learned some. Having heard this,I realize I had heard some of it before. Also, while the concepts are different than Java 8, knowing Java 8 streams really well helps retain this. The syntax similarities help. As do learning the key differences vs learning every API and not thinking about streams at all. And the demo at the end was easy to follow. This presentation reminds me of Java 8 streams in that it took me a few presentations by different people to finally grok it well.