Slide 1

Slide 1 text

Spring-Flavored Kotlin Coroutines Roman Elizarov October 7–10, 2019 Austin Convention Center

Slide 2

Slide 2 text

Speaker: Roman Elizarov Professional developer since 2000 Previously developed high-perf trading software @ Devexperts Teach concurrent & distributed programming @ St. Petersburg ITMO University Chief judge @ Northern Eurasia Contest / ICPC Now team lead in Kotlin Libraries @ JetBrains elizarov @ relizarov

Slide 3

Slide 3 text

Kotlin – Programming Language for

Slide 4

Slide 4 text

Kotlin – Programming Language for

Slide 5

Slide 5 text

Backend evolution Starting with “good old days”

Slide 6

Slide 6 text

ET 1 ET 2 ET N … DB Old-school client-server monolith Clients Executor Threads

Slide 7

Slide 7 text

ET 1 ET 2 ET N … DB Incoming request Clients Executor Threads

Slide 8

Slide 8 text

ET 1 ET 2 ET N … DB Blocks tread Clients Executor Threads

Slide 9

Slide 9 text

ET 1 ET 2 ET N … DB Sizing threads – easy Clients N = number of DB connections Executor Threads

Slide 10

Slide 10 text

Services

Slide 11

Slide 11 text

ET 1 ET 2 ET N … DB Old-school client-server monolith Clients Executor Threads

Slide 12

Slide 12 text

ET 1 ET 2 ET N … DB Now with Services Service Clients Executor Threads

Slide 13

Slide 13 text

ET 1 ET 2 ET N … Services everywhere … Service K Service 1 Service 2 Clients Executor Threads

Slide 14

Slide 14 text

Complex business logic fun placeOrder(order: Order): Response { … }

Slide 15

Slide 15 text

Complex business logic fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) … }

Slide 16

Slide 16 text

Complex business logic fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) … }

Slide 17

Slide 17 text

Complex business logic fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } … }

Slide 18

Slide 18 text

Complex business logic fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } … }

Slide 19

Slide 19 text

Complex business logic fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) }

Slide 20

Slide 20 text

Complex business logic fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) }

Slide 21

Slide 21 text

What if a service is slow? fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) }

Slide 22

Slide 22 text

Slow service @Service class MarginService { private val rest = RestTemplate() fun loadMargin(account: Account): Margin = rest.getForObject( "http://localhost:9090/margin/${account.id}", Margin::class.java)!! }

Slide 23

Slide 23 text

Slow service @Service class MarginService { private val rest = RestTemplate() fun loadMargin(account: Account): Margin = rest.getForObject( "http://localhost:9090/margin/${account.id}", Margin::class.java)!! }

Slide 24

Slide 24 text

Demo Slow service, blocking

Slide 25

Slide 25 text

ET 2 ET N … Clients Blocks threads … Service K Service 1 Service 2 ET 1 Executor Threads

Slide 26

Slide 26 text

ET 2 ET N … Clients Blocks threads … Service K Service 1 Service 2 ET 1 Executor Threads

Slide 27

Slide 27 text

ET 2 ET N … Clients Blocks threads … Service K Service 1 Service 2 ET 1 Executor Threads

Slide 28

Slide 28 text

Code that waits

Slide 29

Slide 29 text

Asynchronous programming Writing code that waits

Slide 30

Slide 30 text

ET 2 ET N … Clients Instead of blocking… … Service K Service 1 Service 2 ET 1 Executor Threads

Slide 31

Slide 31 text

ET 2 ET N … Release the thread … Service K Service 1 Service 2 ET 1 Clients Executor Threads

Slide 32

Slide 32 text

Clients ET 2 ET N … Resume operation later … Service K Service 1 Service 2 ET 1 Executor Threads

Slide 33

Slide 33 text

But how? fun loadMargin(account: Account): Margin

Slide 34

Slide 34 text

But how? Callbacks fun loadMargin(account: Account, callback: (Margin) -> Unit)

Slide 35

Slide 35 text

But how? Callbacks Futures/Promises fun loadMargin(account: Account): CompletableFuture

Slide 36

Slide 36 text

But how? Callbacks Futures/Promises/Reactive fun loadMargin(account: Account): Mono

Slide 37

Slide 37 text

Reactive

Slide 38

Slide 38 text

The logic fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) }

Slide 39

Slide 39 text

Going reactive fun placeOrder(order: Order): Mono

Slide 40

Slide 40 text

Going reactive fun placeOrder(order: Order): Mono =

Slide 41

Slide 41 text

Going reactive fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId)

Slide 42

Slide 42 text

Going reactive fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId) .flatMap { account -> … }

Slide 43

Slide 43 text

Going reactive fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId) .flatMap { account -> if (account.isOptionsAccount) { marginService.loadMargin(account) } else { Mono.just(defaultMargin) } }

Slide 44

Slide 44 text

Going reactive fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId) .flatMap { account -> if (account.isOptionsAccount) { marginService.loadMargin(account) } else { Mono.just(defaultMargin) } }

Slide 45

Slide 45 text

Going reactive fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId) .flatMap { account -> if (account.isOptionsAccount) { marginService.loadMargin(account) } else { Mono.just(defaultMargin) } } .map { margin -> … }

Slide 46

Slide 46 text

Going reactive fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId) .flatMap { account -> if (account.isOptionsAccount) { marginService.loadMargin(account) } else { Mono.just(defaultMargin) } } .map { margin -> validateOrder(order, margin) }

Slide 47

Slide 47 text

Reactive Service @Service class MarginService { private val client = WebClient.create("http://localhost:9090/") fun loadMargin(account: Account): Mono = client .get() .uri("margin/${account.id}") .retrieve() .bodyToMono(Margin::class.java) }

Slide 48

Slide 48 text

Reactive Service @Service class MarginService { private val client = WebClient.create("http://localhost:9090/") fun loadMargin(account: Account): Mono = client .get() .uri("margin/${account.id}") .retrieve() .bodyToMono(Margin::class.java) }

Slide 49

Slide 49 text

Demo: Reactive Was it worth it?

Slide 50

Slide 50 text

Choice 1: Direct code, blocking fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) }

Slide 51

Slide 51 text

Choice 2: Complex code, non-blocking fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId) .flatMap { account -> if (account.isOptionsAccount) { marginService.loadMargin(account) } else { Mono.just(defaultMargin) } } .map { margin -> validateOrder(order, margin) }

Slide 52

Slide 52 text

Why not both?

Slide 53

Slide 53 text

But how? Callbacks Futures/Promises/Reactive fun loadMargin(account: Account): Mono

Slide 54

Slide 54 text

But how? Callbacks Futures/Promises/Reactive Kotlin Coroutines suspend fun loadMargin(account: Account): Margin

Slide 55

Slide 55 text

Direct code: Blocking fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) }

Slide 56

Slide 56 text

Direct code: Coroutines suspend fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) } Write regular code! Call suspending funs

Slide 57

Slide 57 text

Coroutines Service @Service class MarginService { private val client = WebClient.create("http://localhost:9090/") suspend fun loadMargin(account: Account): Margin = client .get() .uri("margin/${account.id}") .retrieve() .awaitBody() }

Slide 58

Slide 58 text

Coroutines Service @Service class MarginService { private val client = WebClient.create("http://localhost:9090/") suspend fun loadMargin(account: Account): Margin = client .get() .uri("margin/${account.id}") .retrieve() .awaitBody() }

Slide 59

Slide 59 text

Demo: Coroutines

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

Suspend behind the scenes suspend fun loadMargin(account: Account): Margin

Slide 62

Slide 62 text

Suspend behind the scenes suspend fun loadMargin(account: Account): Margin fun loadMargin(account: Account, cont: Continuation) But why callback and not future/mono?

Slide 63

Slide 63 text

Performance! Callback is a simple, low-level primitive Integration with async IO libraries is easy

Slide 64

Slide 64 text

Service integration suspend fun loadMargin(account: Account): Margin

Slide 65

Slide 65 text

Service integration suspend fun loadMargin(account: Account): Margin = suspendCoroutine { cont -> // install callback & use cont to resume }

Slide 66

Slide 66 text

Server integrated with coroutines @PostMapping("/order") suspend fun placeOrder(order: Order): Response { … }

Slide 67

Slide 67 text

Server not integrated with coroutines @PostMapping("/order") fun placeOrder(order: Order): Mono = mono { … } Coroutine builder

Slide 68

Slide 68 text

Blocking integration @Component class Initializer { @EventListener(ApplicationStartedEvent::class) fun initData() { … } }

Slide 69

Slide 69 text

Blocking integration @Component class Initializer { @EventListener(ApplicationStartedEvent::class) fun initData() = runBlocking { … } } Coroutine builder

Slide 70

Slide 70 text

Suspend is efficient

Slide 71

Slide 71 text

Suspend is efficient suspend fun placeOrder(order: Order): Response { val account = accountService.loadAccout(order.accountId) val margin = if (account.isOptionsAccount) { marginService.loadMargin(account) } else { defaultMargin } return validateOrder(order, margin) } One object allocated

Slide 72

Slide 72 text

Reactive fun placeOrder(order: Order): Mono = accountService.loadAccount(order.accountId) .flatMap { account -> if (account.isOptionsAccount) { marginService.loadMargin(account) } else { Mono.just(defaultMargin) } } .map { margin -> validateOrder(order, margin) } Lambda allocated* Mono allocated Lambda allocated Mono allocated

Slide 73

Slide 73 text

Let’s go deeper fun placeOrder(params: Params): Mono { // check pre-conditions return actuallyPlaceOrder(order) } fun actuallyPlaceOrder(order: Order): Mono

Slide 74

Slide 74 text

Let’s go deeper (with coroutines) suspend fun placeOrder(params: Params): Response { // check pre-conditions return actuallyPlaceOrder(order) } suspend fun actuallyPlaceOrder(params: Params): Response Tail call optimization Tail call

Slide 75

Slide 75 text

Call stack with coroutines Coroutine Builder placeOrder actuallyPlaceOrder moreLogic marginService.loadMargin suspendCoroutine

Slide 76

Slide 76 text

Call stack with coroutines Coroutine Builder placeOrder actuallyPlaceOrder moreLogic marginService.loadMargin suspendCoroutine unwind Continuation in heap

Slide 77

Slide 77 text

Learn more KotlinConf San Francisco 2017 GOTO Copenhagen 2018

Slide 78

Slide 78 text

Scaling with coroutines With thread pools

Slide 79

Slide 79 text

ET 2 ET N … Clients Thread pools ET 1 Executor Threads

Slide 80

Slide 80 text

ET 2 ET N … Clients Thread pools ET 1 ST 2 ST M1 … S1 1 N = number of CPU cores M1 = depends Service 1 Threads Executor Threads

Slide 81

Slide 81 text

IO-bound (blocking) fun loadAccount(order: Order): Account { // some blocking code here.... }

Slide 82

Slide 82 text

IO-bound suspend fun loadAccount(order: Order): Account { // some blocking code here.... }

Slide 83

Slide 83 text

IO-bound withContext suspend fun loadAccount(order: Order): Account = withContext(dispatcher) { // some blocking code here.... }

Slide 84

Slide 84 text

IO-bound withContext suspend fun loadAccount(order: Order): Account = withContext(dispatcher) { // some blocking code here.... } val dispatcher = Executors.newFixedThreadPool(M2).asCoroutineDispatcher()

Slide 85

Slide 85 text

CPU-bound code fun validateOrder(order: Order, margin: Margin): Response { // perform CPU-consuming computation }

Slide 86

Slide 86 text

CPU-bound code suspend fun validateOrder(order: Order, margin: Margin): Response = withContext(compute) { // perform CPU-consuming computation } val compute = Executors.newFixedThreadPool(M3).asCoroutineDispatcher()

Slide 87

Slide 87 text

ET 2 ET N … Clients Fine-grained control and encapsulation ET 1 S1 1 ST M1 Service 2 Threads S1 1 ST M2 Service 3 Threads S1 1 ST M3 Async IO-bound CPU- bound Never blocked Service 1 Threads Executor Threads

Slide 88

Slide 88 text

But there’s more!

Slide 89

Slide 89 text

Cancellation

Slide 90

Slide 90 text

withTimeout suspend fun placeOrder(order: Order): Response = withTimeout(1000) { // code before loadMargin(account) // code after }

Slide 91

Slide 91 text

withTimeout propagation suspend fun placeOrder(order: Order): Response = withTimeout(1000) { // code before loadMargin(account) // code after } suspend fun loadMargin(account: Account): Margin = suspendCoroutine { cont -> // install callback & use cont to resume }

Slide 92

Slide 92 text

withTimeout propagation suspend fun placeOrder(order: Order): Response = withTimeout(1000) { // code before loadMargin(account) // code after } suspend fun loadMargin(account: Account): Margin = suspendCancellableCoroutine { cont -> // install callback & use cont to resume }

Slide 93

Slide 93 text

withTimeout propagation suspend fun placeOrder(order: Order): Response = withTimeout(1000) { // code before loadMargin(account) // code after } suspend fun loadMargin(account: Account): Margin = suspendCancellableCoroutine { cont -> // install callback & use cont to resume cont.invokeOnCancellation { … } }

Slide 94

Slide 94 text

Concurrency Multiple things at the same time

Slide 95

Slide 95 text

Example fun placeOrder(order: Order): Response { val account = accountService.loadAccount(order) val margin = marginService.loadMargin(order) return validateOrder(order, account, margin) }

Slide 96

Slide 96 text

Example fun placeOrder(order: Order): Response { val account = accountService.loadAccount(order) val margin = marginService.loadMargin(order) return validateOrder(order, account, margin) } No data dependencies

Slide 97

Slide 97 text

Concurrency with async (futures) fun placeOrder(order: Order): Response { val account = accountService.loadAccountAsync(order) val margin = marginService.loadMarginAsync(order) return validateOrder(order, account.await(), margin.await()) }

Slide 98

Slide 98 text

Concurrency with async (futures) fun placeOrder(order: Order): Response { val account = accountService.loadAccountAsync(order) val margin = marginService.loadMarginAsync(order) return validateOrder(order, account.await(), margin.await()) }

Slide 99

Slide 99 text

Concurrency with async (futures) fun placeOrder(order: Order): Response { val account = accountService.loadAccountAsync(order) val margin = marginService.loadMarginAsync(order) return validateOrder(order, account.await(), margin.await()) } Fails?

Slide 100

Slide 100 text

Concurrency with async (futures) fun placeOrder(order: Order): Response { val account = accountService.loadAccountAsync(order) val margin = marginService.loadMarginAsync(order) return validateOrder(order, account.await(), margin.await()) } Fails? Leaks !

Slide 101

Slide 101 text

Structured concurrency

Slide 102

Slide 102 text

Concurrency with coroutines suspend fun placeOrder(order: Order): Response = coroutineScope { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } validateOrder(order, account.await(), margin.await()) }

Slide 103

Slide 103 text

Concurrency with coroutines suspend fun placeOrder(order: Order): Response = coroutineScope { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } validateOrder(order, account.await(), margin.await()) }

Slide 104

Slide 104 text

Concurrency with coroutines suspend fun placeOrder(order: Order): Response = coroutineScope { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } validateOrder(order, account.await(), margin.await()) }

Slide 105

Slide 105 text

Concurrency with coroutines suspend fun placeOrder(order: Order): Response = coroutineScope { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } validateOrder(order, account.await(), margin.await()) } Fails?

Slide 106

Slide 106 text

Concurrency with coroutines suspend fun placeOrder(order: Order): Response = coroutineScope { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } validateOrder(order, account.await(), margin.await()) } Fails? Cancels

Slide 107

Slide 107 text

Concurrency with coroutines suspend fun placeOrder(order: Order): Response = coroutineScope { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } validateOrder(order, account.await(), margin.await()) } Fails? Cancels Cancels

Slide 108

Slide 108 text

Concurrency with coroutines suspend fun placeOrder(order: Order): Response = coroutineScope { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } validateOrder(order, account.await(), margin.await()) } Waits for completion of all children

Slide 109

Slide 109 text

Enforcing structure

Slide 110

Slide 110 text

Without coroutine scope? suspend fun placeOrder(order: Order): Response { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } return validateOrder(order, account.await(), margin.await()) }

Slide 111

Slide 111 text

Without coroutine scope? suspend fun placeOrder(order: Order): Response { val account = async { accountService.loadAccount(order) } val margin = async { marginService.loadMargin(order) } return validateOrder(order, account.await(), margin.await()) } ERROR: Unresolved reference.

Slide 112

Slide 112 text

Extensions of CoroutineScope fun CoroutineScope.async( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T ): Deferred

Slide 113

Slide 113 text

Convention fun CoroutineScope.bg(params: Params) = launch { // … } Launches new coroutine

Slide 114

Slide 114 text

Types as documentation fun foo(params: Params): Response suspend fun foo(params: Params): Response fun CoroutineScope.foo(params: Params): Response Fast, local Remote, or slow Side effect - bg

Slide 115

Slide 115 text

Types are enforced fun foo(params: Params): Response suspend fun foo(params: Params): Response fun CoroutineScope.foo(params: Params): Response Not allowed But must provide scope explicitly Using coroutineScope { … } Fast, local Remote, or slow Side effect - bg

Slide 116

Slide 116 text

Green threads / fibers Alternative way to async

Slide 117

Slide 117 text

Green threads / Fibers ET 2 ET N … ET 1 F 2 F M … Fibers F 1 ~ Coroutines Hidden from developer Executor Threads

Slide 118

Slide 118 text

But marking with suspend pays off at scale Fibers – everything suspending

Slide 119

Slide 119 text

Thread switching And how to avoid it

Slide 120

Slide 120 text

ET 2 ET N … Clients Threads ET 1 S1 1 ST M1 S1 1 ST M2 S1 1 ST M3 Service 2 Threads Service 3 Threads Service 1 Threads Executor Threads

Slide 121

Slide 121 text

ET 2 ET N … Clients Solution – shared thread pool ET 1 Executor Threads

Slide 122

Slide 122 text

ET 2 ET N … Clients Solution – shared thread pool ET 1 Executor Threads

Slide 123

Slide 123 text

ET 2 ET N … Clients Solution – shared thread pool ET 1 ET N+1 Executor Threads

Slide 124

Slide 124 text

ET 2 ET N … Clients Solution – shared thread pool ET 1 ET N+1 ET N+2 Executor Threads

Slide 125

Slide 125 text

ET 2 ET N … Clients Solution – shared thread pool ET 1 ET N+1 … ET M ET N+2 ET N+M Executor Threads

Slide 126

Slide 126 text

withContext for IO suspend fun loadAccount(order: Order): Account = withContext(dispatcher) { // some blocking code here.... } val dispatcher = Executors.newFixedThreadPool(M2).asCoroutineDispatcher()

Slide 127

Slide 127 text

withContext for Dispatсhers.IO suspend fun loadAccount(order: Order): Account = withContext(Dispatchers.IO) { // some blocking code here.... } No thread switch from Dispatchers.Default pool

Slide 128

Slide 128 text

ET 2 ET N … Clients Solution – shared thread pool ET 1 Dispatchers.Default Executor Threads

Slide 129

Slide 129 text

ET 2 ET N … Clients Solution – shared thread pool ET 1 ET N+1 … ET M ET N+2 ET N+M Dispatchers.Default Dispatchers.IO Executor Threads

Slide 130

Slide 130 text

Coroutines and data streams

Slide 131

Slide 131 text

Returning many responses suspend fun foo(params: Params): Response One response suspend fun foo(params: Params): List Many responses

Slide 132

Slide 132 text

Returning many responses suspend fun foo(params: Params): Response One response suspend fun foo(params: Params): List Many responses fun foo(params: Params): Flow Many responses async

Slide 133

Slide 133 text

Kotlin Flows Reactive streams for coroutines

Slide 134

Slide 134 text

fun foo(): Flow ~ Reactive Publisher / Flux

Slide 135

Slide 135 text

fun foo(): Flow = flow { … }

Slide 136

Slide 136 text

fun foo(): Flow = flow { for (i in 1..10) { emit(i) delay(100) } }

Slide 137

Slide 137 text

fun foo(): Flow = flow { for (i in 1..10) { emit(i) delay(100) } } suspend fun main() { foo().collect { x -> println(x) } }

Slide 138

Slide 138 text

fun foo(): Flow = flow { for (i in 1..10) { emit(i) delay(100) } } suspend fun main() { foo() } Flow is cold: describes the data, does not run it until collected

Slide 139

Slide 139 text

Flow operators fun foo(): Flow = flow { for (i in 1..10) { emit(i) delay(100) } } suspend fun main() { foo() .map { it * it } .toList() }

Slide 140

Slide 140 text

Why flow?

Slide 141

Slide 141 text

A A’ mapper fun map(mapper: (T) -> R): Flux fun flatMap(mapper: (T) -> Publisher): Flux Synchronous Asynchronous Flux

Slide 142

Slide 142 text

A A’ mapper fun map(mapper: (T) -> R): Flux fun flatMap(mapper: (T) -> Publisher): Flux fun filter(predicate: (T) -> Boolean): Flux A A predicate Synchronous Asynchronous Synchronous Asynchronous Flux fun filterWhen(predicate: (T) -> Publisher): Flux

Slide 143

Slide 143 text

A A’ Flow fun map(transform: suspend (T) -> R): Flow transform

Slide 144

Slide 144 text

A A’ transform Flow fun map(transform: suspend (T) -> R): Flow

Slide 145

Slide 145 text

A A’ transform fun map(transform: suspend (T) -> R): Flow Flow fun filter(predicate: suspend (T) -> Boolean): Flow A predicate A

Slide 146

Slide 146 text

Operator avoidance startWith(value) onStart { emit(value) } delaySubscription(time) onStart { delay(time) } startWith(flow) onStart { emitAll(flow) } delayElements(time) onEach { delay(time) } onErrorReturn(value) catch { emit(value) } onErrorResume(flow) catch { emitAll(flow) } generate(…) flow { … } Composable

Slide 147

Slide 147 text

Reactive + = ❤

Slide 148

Slide 148 text

Spring ❤ Flow @GetMapping("/sse/{n}", produces = [MediaType.TEXT_EVENT_STREAM_VALUE]) fun greetings(@PathVariable n: String): Flow

Slide 149

Slide 149 text

Spring ❤ Flow @GetMapping("/sse/{n}", produces = [MediaType.TEXT_EVENT_STREAM_VALUE]) fun greetings(@PathVariable n: String): Flow = flow { while(true) { emit(Greeting("Hello from coroutines $n @ ${Instant.now()}")) delay(1000) } }

Slide 150

Slide 150 text

Demo: Spring Flow Support

Slide 151

Slide 151 text

Thank you Questions? elizarov @ relizarov

Slide 152

Slide 152 text

Kotlin Coroutines For The Win! #springone @s1p