Share
Embed
Going with the Flow: Coroutines 1.3.x
Let’s talk reactive coroutines. The coroutines 1.3.0 release graduated Flow to stable, and introduced breaking changes to the Channel api.
When do we use Channels, and when do we use Flows? How do we maintain structured concurrency in our code, and how do we test it? Do we need to re-write our apps into MVFlow?
In this talk, we’ll evaluate the options for reactive programming with coroutines. We’ll go over Android-specific problems and how to fit their solutions into any existing architecture.
Rick Busarow
November 24, 2019
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
168 slides
-
GOING WITH THE FLOW Droidcon San Francisco Nov 26, 2019
rbusarow Rick Busarow COROUTINES 1.3.X -
@rbusarow fun doSomethingSlow() { api.getAllData() .enqueue { ... } }
interface Api { @GET(“/all") fun getAllData(): Call<List<Data>> } Suspend -
@rbusarow fun doSomethingSlow() { api.getAllData() .enqueue { ... } }
interface Api { @GET(“/all") fun getAllData(): Call<List<Data>> } Suspend asynchronous -
@rbusarow Suspend domain logic IO library request + callback callbacks
callback resource -
@rbusarow Suspend domain logic IO library request + callback callbacks
callback resource request -
@rbusarow Suspend domain logic IO library request + callback callbacks
callback resource request response -
@rbusarow Suspend domain logic IO library request + callback callbacks
callback callback resource request response -
@rbusarow Suspend domain logic IO library request + callback callbacks
callback callback callback(response) resource request response -
@rbusarow fun doSomethingSlow() { api.getAllData() .enqueue { ... } }
interface Api { @GET(“/all") fun getAllData(): Call<List<Data>> } Suspend -
@rbusarow fun doSomethingSlow() { api.getAllData() .enqueue { ... } }
interface Api { @GET(“/all") suspend fun getAllData(): List<Data> } Suspend -
@rbusarow fun doSomethingSlow() { api.getAllData() } interface Api { @GET(“/all”)
suspend fun getAllData(): List<Data> } Suspend -
@rbusarow fun doSomethingSlow() { api.getAllData() } interface Api { @GET(“/all”)
suspend fun getAllData(): List<Data> } Suspend suspend function ‘getAllData’ should be called only from a coroutine or another suspend function -
@rbusarow suspend fun doSomethingSlow() { api.getAllData() } interface Api {
@GET(“/all") suspend fun getAllData(): List<Data> } Suspend -
@rbusarow suspend fun doSomethingSlow() { api.getAllData() } interface Api {
@GET(“/all") suspend fun getAllData(): List<Data> } Suspend -
@rbusarow suspend fun doSomethingSlow() { api.getAllData() } interface Api {
@GET(“/all") suspend fun getAllData(): List<Data> } Suspend Hey compiler! Turn this into a callback! -
@rbusarow suspend fun doSomethingSlow() { api.getAllData() } interface Api {
@GET(“/all") suspend fun getAllData(): List<Data> } interface Continuation<in T> { val context: CoroutineContext fun resumeWith(result: Result<T>) } Suspend -
@rbusarow suspend fun doSomethingSlow() { api.getAllData() } interface Api {
@GET(“/all") fun getAllData(continuation: Continuation<List<Data>>) } interface Continuation<in T> { val context: CoroutineContext fun resumeWith(result: Result<T>) } Suspend -
@rbusarow fun doSomethingSlow(continuation: Continuation<Unit>) { api.getAllData(object : Continuation<List<Data>> { override
val context = continuation.context override fun resumeWith(result: Result<List<Data>>) { continuation.resumeWith(Result.success(Unit)) } }) } interface Api { @GET(“/all") fun getAllData(continuation: Continuation<List<Data>>) } Suspend -
@rbusarow fun doSomethingSlow(continuation: Continuation<Unit>) { api.getAllData(object : Continuation<List<Data>> { override
val context = continuation.context override fun resumeWith(result: Result<List<Data>>) { continuation.resumeWith(Result.success(Unit)) } }) } interface Api { @GET(“/all") fun getAllData(continuation: Continuation<List<Data>>) } Suspend -
@rbusarow fun doSomethingSlow(continuation: Continuation<Unit>) { api.getAllData(object : Continuation<List<Data>> { override
val context = continuation.context override fun resumeWith(result: Result<List<Data>>) { continuation.resumeWith(Result.success(Unit)) } }) } interface Api { @GET(“/all") fun getAllData(continuation: Continuation<List<Data>>) } Suspend -
@rbusarow fun doSomethingSlow(continuation: Continuation<Unit>) { api.getAllData(object : Continuation<List<Data>> { override
val context = continuation.context override fun resumeWith(result: Result<List<Data>>) { continuation.resumeWith(Result.success(Unit)) } }) } interface Api { @GET(“/all") fun getAllData(continuation: Continuation<List<Data>>) } Suspend -
@rbusarow fun doSomethingSlow(continuation: Continuation<Unit>) { api.getAllData(object : Continuation<List<Data>> { override
val context = continuation.context override fun resumeWith(result: Result<List<Data>>) { continuation.resumeWith(Result.success(Unit)) } }) } interface Api { @GET(“/all") fun getAllData(continuation: Continuation<List<Data>>) } Suspend -
Coroutine A sender Coroutine B receiver Channels Solution for shared
mutable state Suspending queue Bridges the gap between different coroutines @rbusarow -
Coroutine A sender Coroutine B receiver Channels Solution for shared
mutable state Suspending queue Bridges the gap between different coroutines @rbusarow -
@rbusarow interface Channel<E> : SendChannel<E>, ReceiveChannel<E> interface SendChannel<in E> {
suspend fun send(element: E) fun offer(element: E): Boolean } interface ReceiveChannel<out E> { suspend fun receive(): E fun poll(): E? operator fun iterator(): ChannelIterator<E> } Channels -
@rbusarow interface Channel<E> : SendChannel<E>, ReceiveChannel<E> interface SendChannel<in E> {
suspend fun send(element: E) fun offer(element: E): Boolean } interface ReceiveChannel<out E> { suspend fun receive(): E fun poll(): E? operator fun iterator(): ChannelIterator<E> } Channels -
@rbusarow interface Channel<E> : SendChannel<E>, ReceiveChannel<E> interface SendChannel<in E> {
suspend fun send(element: E) fun offer(element: E): Boolean } interface ReceiveChannel<out E> { suspend fun receive(): E fun poll(): E? operator fun iterator(): ChannelIterator<E> } Channels -
@rbusarow suspend fun main() { val channel = Channel<Int>() repeat(3)
{ channel.send(it) println("sent $it") } } Channels -
@rbusarow suspend fun main() = coroutineScope { val channel =
Channel<Int>() launch { for (i in channel) { println("received $i") } } repeat(3) { println("sent $it”) channel.send(it) } channel.cancel() } Channels -
@rbusarow suspend fun main() = coroutineScope { val channel =
Channel<Int>() launch { for (i in channel) { println("received $i") } } repeat(3) { println("sent $it”) channel.send(it) } channel.cancel() } Channels -
@rbusarow suspend fun main() = coroutineScope { val channel =
Channel<Int>() launch { for (i in channel) { println("received $i") } } repeat(3) { println("sent $it”) channel.send(it) } channel.cancel() } Channels -
@rbusarow suspend fun main() = coroutineScope { val channel =
Channel<Int>() launch { for (i in channel) { println("received $i") } } repeat(3) { println("sent $it”) channel.send(it) } channel.cancel() } Channels -
@rbusarow suspend fun main() = coroutineScope { val channel =
Channel<Int>() launch { for (i in channel) { println("received $i") } } repeat(3) { println("sent $it”) channel.send(it) } channel.cancel() } Channels output: -
@rbusarow suspend fun main() = coroutineScope { val channel =
Channel<Int>() launch { for (i in channel) { println("received $i") } } repeat(3) { println("sent $it”) channel.send(it) } channel.cancel() } Channels sent 0 received 0 sent 1 received 1 sent 2 received 2 output: -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow buffer = 2 Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
Coroutine A sender Coroutine B receiver Rendezvous Unlimited Array(size) Conflated
@rbusarow Backpressure -
@rbusarow fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel
= Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { channel.sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) channel.invokeOnClose { locationClient.removeLocationUpdates(callback) } return channel } https://youtu.be/P7ov_r1JZ1g?t=2188 -
@rbusarow fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel
= Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { channel.sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) channel.invokeOnClose { locationClient.removeLocationUpdates(callback) } return channel } https://youtu.be/P7ov_r1JZ1g?t=2188 -
@rbusarow fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel
= Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { channel.sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) channel.invokeOnClose { locationClient.removeLocationUpdates(callback) } return channel } https://youtu.be/P7ov_r1JZ1g?t=2188 -
@rbusarow fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel
= Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { channel.sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) channel.invokeOnClose { locationClient.removeLocationUpdates(callback) } return channel } https://youtu.be/P7ov_r1JZ1g?t=2188 -
@rbusarow fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel
= Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { channel.sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) channel.invokeOnClose { locationClient.removeLocationUpdates(callback) } return channel } https://youtu.be/P7ov_r1JZ1g?t=2188 -
@rbusarow fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel
= Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { channel.sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) channel.invokeOnClose { locationClient.removeLocationUpdates(callback) } return channel } https://youtu.be/P7ov_r1JZ1g?t=2188 -
BroadcastChannels Send data to multiple coroutines via .openSubscription() The buffer
is on the BroadcastChannel side Shared between all consumers @rbusarow -
@rbusarow suspend fun main() = coroutineScope { val channel =
Channel<Int>() launch { for (i in channel) { println("received $i") } } repeat(3) { println("sent $it”) channel.send(it) } channel.cancel() } BroadcastChannels -
suspend fun main() = coroutineScope { val broadcastChannel = BroadcastChannel<Int>(capacity
= 1) val b: ReceiveChannel<Int> = broadcastChannel.openSubscription() val c: ReceiveChannel<Int> = broadcastChannel.openSubscription() launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } @rbusarow BroadcastChannels -
suspend fun main() = coroutineScope { val broadcastChannel = BroadcastChannel<Int>(capacity
= 1) val b: ReceiveChannel<Int> = broadcastChannel.openSubscription() val c: ReceiveChannel<Int> = broadcastChannel.openSubscription() launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } @rbusarow BroadcastChannels -
suspend fun main() = coroutineScope { val broadcastChannel = BroadcastChannel<Int>(capacity
= 1) val b: ReceiveChannel<Int> = broadcastChannel.openSubscription() val c: ReceiveChannel<Int> = broadcastChannel.openSubscription() launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } @rbusarow BroadcastChannels -
suspend fun main() = coroutineScope { val broadcastChannel = BroadcastChannel<Int>(capacity
= 1) val b: ReceiveChannel<Int> = broadcastChannel.openSubscription() val c: ReceiveChannel<Int> = broadcastChannel.openSubscription() launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } @rbusarow BroadcastChannels -
suspend fun main() = coroutineScope { val broadcastChannel = BroadcastChannel<Int>(capacity
= 1) val b: ReceiveChannel<Int> = broadcastChannel.openSubscription() val c: ReceiveChannel<Int> = broadcastChannel.openSubscription() launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } @rbusarow BroadcastChannels -
Coroutine C Coroutine B receiver Coroutine A sender 0 @rbusarow
BroadcastChannels receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } broadcast b C -
broadcast b C Coroutine C Coroutine B receiver Coroutine A
sender 0 @rbusarow BroadcastChannels receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } -
broadcast b C Coroutine C Coroutine B receiver Coroutine A
sender 0 @rbusarow BroadcastChannels receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } 0 -
broadcast b C Coroutine C Coroutine B receiver Coroutine A
sender @rbusarow BroadcastChannels receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } 0 0 -
broadcast b C Coroutine C Coroutine B receiver Coroutine A
sender 0 0 @rbusarow BroadcastChannels receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } -
Coroutine C Coroutine B receiver Coroutine A sender 0 @rbusarow
BroadcastChannels receiver 0 suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } broadcast b C -
Coroutine C Coroutine B receiver Coroutine A sender @rbusarow BroadcastChannels
receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } broadcast b C -
Coroutine C Coroutine B receiver Coroutine A sender @rbusarow BroadcastChannels
receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } broadcast b C -
Coroutine C Coroutine A sender @rbusarow BroadcastChannels receiver suspend fun
main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } broadcast b C -
Coroutine C Coroutine A sender @rbusarow BroadcastChannels receiver 1 suspend
fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } broadcast b C -
broadcast b C Coroutine C Coroutine A sender @rbusarow BroadcastChannels
receiver 1 suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } -
broadcast b C Coroutine C Coroutine A sender @rbusarow BroadcastChannels
receiver 1 suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } 1 -
broadcast b C Coroutine C Coroutine A sender @rbusarow BroadcastChannels
receiver 1 suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } 1 -
broadcast b C Coroutine C Coroutine A sender @rbusarow BroadcastChannels
receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } 1 1 -
broadcast b C Coroutine C Coroutine A sender @rbusarow BroadcastChannels
receiver 1 suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } 1 -
broadcast b C Coroutine A sender @rbusarow BroadcastChannels Coroutine C
receiver suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } 1 -
broadcast b C Coroutine A sender @rbusarow BroadcastChannels 1 Coroutine
C receiver 2 suspend fun main() = coroutineScope { ... launch { b.receive() } launch { for (i in c) { ... } } repeat(3) { broadcastChannel.send(it) } } -
@rbusarow ConflatedBroadcastChannel MutableLiveData Current property .value .value Emit lossless .send(value)
.sendBlocking(value) .offer(value) .setValue(value) (main thread only) Emit lossy - - - .postValue(value) Multiple observers? yes Yes Backpressure? None None -
@rbusarow Job hierarchy Job Job Job Job Job Job Job
Job Job Job Job -
Job @rbusarow Job hierarchy Job Job Job Job Job Job
Job Job Job Job .cancel() Job Job Job -
Job @rbusarow Job hierarchy Job Job Job Job Job Job
Job Job Job Job Job .cancel() -
@rbusarow suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit
) = coroutineScope { val done = CompletableDeferred<Unit>() val callback = object : LocationCallback() { val mutex = Mutex(false) var observeJob: Job? = null override fun onLocationResult(result: LocationResult) { observeJob?.cancel() observeJob = launch { mutex.withLock { observer(result) } } } } try { locationClient.requestLocationUpdates(request, callback, Looper.myLooper()) done.await() } finally { locationClient.removeLocationUpdates(callback) } } https://youtu.be/EOjq4OIWKqM?t=1994 -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
= coroutineScope { val done = CompletableDeferred<Unit>() val callback = object : LocationCallback() { val mutex = Mutex(false) var observeJob: Job? = null override fun onLocationResult(result: LocationResult) { observeJob?.cancel() observeJob = launch { mutex.withLock { observer(result) } } } } try { locationClient.requestLocationUpdates(request, callback, Looper.myLooper()) done.await() } finally { locationClient.removeLocationUpdates(callback) } } @rbusarow https://youtu.be/EOjq4OIWKqM?t=1994 -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
= coroutineScope { val done = CompletableDeferred<Unit>() val callback = object : LocationCallback() { val mutex = Mutex(false) var observeJob: Job? = null override fun onLocationResult(result: LocationResult) { observeJob?.cancel() observeJob = launch { mutex.withLock { observer(result) } } } } try { locationClient.requestLocationUpdates(request, callback, Looper.myLooper()) done.await() } finally { locationClient.removeLocationUpdates(callback) } } @rbusarow https://youtu.be/EOjq4OIWKqM?t=1994 -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
= coroutineScope { val done = CompletableDeferred<Unit>() val callback = object : LocationCallback() { val mutex = Mutex(false) var observeJob: Job? = null override fun onLocationResult(result: LocationResult) { observeJob?.cancel() observeJob = launch { mutex.withLock { observer(result) } } } } try { locationClient.requestLocationUpdates(request, callback, Looper.myLooper()) done.await() } finally { locationClient.removeLocationUpdates(callback) } } @rbusarow https://youtu.be/EOjq4OIWKqM?t=1994 -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
= coroutineScope { val done = CompletableDeferred<Unit>() val callback = object : LocationCallback() { val mutex = Mutex(false) var observeJob: Job? = null override fun onLocationResult(result: LocationResult) { observeJob?.cancel() observeJob = launch { mutex.withLock { observer(result) } } } } try { locationClient.requestLocationUpdates(request, callback, Looper.myLooper()) done.await() } finally { locationClient.removeLocationUpdates(callback) } } @rbusarow https://youtu.be/EOjq4OIWKqM?t=1994 -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
= coroutineScope { val done = CompletableDeferred<Unit>() val callback = object : LocationCallback() { val mutex = Mutex(false) var observeJob: Job? = null override fun onLocationResult(result: LocationResult) { observeJob?.cancel() observeJob = launch { mutex.withLock { observer(result) } } } } try { locationClient.requestLocationUpdates(request, callback, Looper.myLooper()) done.await() } finally { locationClient.removeLocationUpdates(callback) } } @rbusarow https://youtu.be/EOjq4OIWKqM?t=1994 -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
@rbusarow Iterating toward Flow -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
@rbusarow Iterating toward Flow way too specific -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) @rbusarow Listenable<T> -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) @rbusarow Listenable<T> member function? -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) @rbusarow Listenable<T> -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) @rbusarow Listenable<T> no coroutine support? -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) @rbusarow Listenable<T> no coroutine support? -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: suspend (T) -> Unit) @rbusarow Listenable<T> -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: suspend (T) -> Unit) @rbusarow Listenable<T> Guaranteed to be in a coroutine -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: suspend (T) -> Unit) suspend inline fun <T> Listenable<T>.listen(listener: (T) -> Unit) @rbusarow Listenable<T> -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: suspend (T) -> Unit) suspend inline fun <T> Listenable<T>.listen(listener: (T) -> Unit) suspend fun onNewListenable(listenable: Listenable<Int>) { listenable.listen { delay(1000) println("I'm listening to $it in a coroutine”) } } @rbusarow Listenable<T> -
suspend fun observeLocation( request: LocationRequest, observer: (LocationResult) -> Unit )
suspend fun <T> listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: (T) -> Unit) suspend fun <T> Listenable<T>.listen(listener: suspend (T) -> Unit) suspend inline fun <T> Listenable<T>.listen(listener: (T) -> Unit) suspend fun onNewListenable(listenable: Listenable<Int>) { listenable.listen { delay(1000) println("I'm listening to $it in a coroutine”) } } @rbusarow Listenable<T> -
Flow somewhat stable as of coroutines 1.3.0 some operators and
builders are still in preview Channel-based functionality is still experimental @rbusarow -
@rbusarow class SomeClass { val lastName = findLastName() private fun
findLastName() = "Rida" } Flow -
@rbusarow class SomeClass { val lastName = findLastName() val legalName
by lazy { "Tramar Lacel Dillard" } private fun findLastName() = "Rida" } Flow -
@rbusarow class SomeClass { val firstName = { "Flo" }
val lastName = findLastName() val legalName by lazy { "Tramar Lacel Dillard" } private fun findLastName() = "Rida" } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { repeat(3) { emit(it) } } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { repeat(3) { emit(it) } } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { repeat(3) { emit(it) } } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.collect { number: Int -> println("collecting $number") } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.collect { number: Int -> println("collecting $number") } } Flow Flow builder Flow collector -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.collect { number: Int -> println("collecting $number") } } Flow output: -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.collect { number: Int -> println("collecting $number") } } Flow starting collecting 0 collecting 1 collecting 2 all done output: -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.collect { number: Int -> println("collecting $number") } numbers.collect { number: Int -> println("collecting $number again") } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.collect { number: Int -> println("collecting $number") } numbers.collect { number: Int -> println("collecting $number again") } } Flow output: -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.collect { number: Int -> println("collecting $number") } numbers.collect { number: Int -> println("collecting $number again") } } Flow starting collecting 0 collecting 1 collecting 2 all done starting collecting 0 again collecting 1 again collecting 2 again all done output: -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.filter { it % 2 == 0 } .collect { number: Int -> println("collecting $number") } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.filter { it % 2 == 0 } .collect { number: Int -> println("collecting $number") } } Flow output: -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.filter { it % 2 == 0 } .collect { number: Int -> println("collecting $number") } } Flow starting collecting 0 collecting 2 all done output: -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers .collect { numberString: String -> println("collecting $numberString") } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.take(2) .collect { numberString: String -> println("collecting $numberString”) } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.take(2) .collect { number: Int -> println("collecting $number”) } } Flow output: never printed -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
"c") val numbers = flow<Int> { println("starting") repeat(3) { emit(it) } println("all done") } numbers.take(2) .collect { number: Int -> println("collecting $number”) } } Flow starting collecting 0 collecting 1 output: never printed -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
“c”) val numbers = flowOf(1, 2, 3) } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
“c”) val numbers = flowOf(1, 2, 3) val pairs: Flow<Flow<Any>> = listOf(letters, numbers).asFlow() } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
“c”) val numbers = flowOf(1, 2, 3) val pairs: Flow<Flow<Any>> = listOf(letters, numbers).asFlow() val events: Flow<Any> = all.flattenMerge(2) } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
“c”) val numbers = flowOf(1, 2, 3) val pairs: Flow<Flow<Any>> = listOf(letters, numbers).asFlow() val events: Flow<Any> = all.flattenMerge(2) events.collect { when(it) { is String -> println("collecting String : $it") is Int -> println("collecting Int : $it") } } } Flow -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
“c”) val numbers = flowOf(1, 2, 3) val pairs: Flow<Flow<Any>> = listOf(letters, numbers).asFlow() val events: Flow<Any> = all.flattenMerge(2) events.collect { when(it) { is String -> println("collecting String : $it") is Int -> println("collecting Int : $it") } } } Flow buffer size -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
“c”) val numbers = flowOf(1, 2, 3) val pairs: Flow<Flow<Any>> = listOf(letters, numbers).asFlow() val events: Flow<Any> = all.flattenMerge(2) events.collect { when(it) { is String -> println("collecting String : $it") is Int -> println("collecting Int : $it") } } } Flow output: -
@rbusarow suspend fun main() { val letters = flowOf("a", "b",
“c”) val numbers = flowOf(1, 2, 3) val pairs: Flow<Flow<Any>> = listOf(letters, numbers).asFlow() val events: Flow<Any> = all.flattenMerge(2) events.collect { when(it) { is String -> println("collecting String : $it") is Int -> println("collecting Int : $it") } } } Flow collecting String : a collecting Int : 1 collecting Int : 2 collecting Int : 3 collecting String : b collecting String : c output: -
@rbusarow class SomeViewModel { private val _channel = ConflatedBroadcastChannel(1) val
flow: Flow<Int> get() = _channel.asFlow() init { _channel.sendBlocking(2) } } ConflatedBroadcastChannel usage Send from anywhere -
@rbusarow class SomeLocationService @Inject constructor( private val locationClient: FusedLocationProviderClient, coroutineScope:
CoroutineScope ) { private val locationRequest = LocationRequest().apply { fastestInterval = 1000 interval = 1000 priority = LocationRequest.PRIORITY_HIGH_ACCURACY } ... } http://bit.ly/BroadcastFlow -
@rbusarow priority = LocationRequest.PRIORITY_HIGH_ACCURACY } val locations: Flow<Location> = broadcastFlow(coroutineScope)
{ val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { sendBlockingOrNull(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) awaitClose { locationClient.removeLocationUpdates(callback) } } } http://bit.ly/BroadcastFlow -
@rbusarow priority = LocationRequest.PRIORITY_HIGH_ACCURACY } val locations: Flow<Location> = broadcastFlow(coroutineScope)
{ val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { sendBlockingOrNull(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) awaitClose { locationClient.removeLocationUpdates(callback) } } } http://bit.ly/BroadcastFlow -
@rbusarow priority = LocationRequest.PRIORITY_HIGH_ACCURACY } val locations: Flow<Location> = broadcastFlow(coroutineScope)
{ val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) awaitClose { locationClient.removeLocationUpdates(callback) } } } http://bit.ly/BroadcastFlow -
@rbusarow priority = LocationRequest.PRIORITY_HIGH_ACCURACY } val locations: Flow<Location> = broadcastFlow(coroutineScope)
{ val callback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { sendBlocking(locationResult.lastLocation) } } locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() ) awaitClose { locationClient.removeLocationUpdates(callback) } } } http://bit.ly/BroadcastFlow -
@rbusarow Slides: bit.ly/GoingWithTheFlow13x Jetbrains docs: https://kotlinlang.org/docs/reference/coroutines/flow.html Android Suspenders at KotlinConf:
https://youtu.be/P7ov_r1JZ1g Android Suspenders at ADS ’18: https://youtu.be/EOjq4OIWKqM LiveData with Coroutines and Flow at ADS ’19: https://youtu.be/B8ppnjGPAGE rbusarow Rick Busarow