Share
Embed
Android Suspenders
So you’ve read the Coroutines guide and you’re ready to start using them in your Android app to coroutines? Great!
This talk will focus on the best practices of using coroutines in your app, including how to handle lifecycle changes with Architecture Components, integration with background job processing, and moving away from RxJava.
Chris Banes
October 04, 2018
Transcript
193 slides
-
Android’s main thread measure + layout draw View inflation and
many more things -
C R U D reate ead pdate elete What does
your typical mobile app do? -
So why coroutines? Scale on limited hardware Easier development model
Great for I/O tasks -
-core -android -rx2 jars: 774KB apk: 499KB 3260 method refs
r8: 113KB 1208 method refs -
-core -android -rx2 jars: 774KB apk: 499KB 3260 method refs
r8: 113KB 1208 method refs r8 optimized: 99KB 834 method refs -
override suspend fun updateShow(showId: Long) { val localResult = localShowStore.getShow(showId)
val result1 = remoteSource1.getShow(showId) val result2 = remoteSource2.getShow(showId) val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. -
override suspend fun updateShow(showId: Long) { val localResult = localShowStore.getShow(showId)
val result1 = remoteSource1.getShow(showId) val result2 = remoteSource2.getShow(showId) val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. 1 -
override suspend fun updateShow(showId: Long) { val localResult = localShowStore.getShow(showId)
val result1 = remoteSource1.getShow(showId) val result2 = remoteSource2.getShow(showId) val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. 1 2 -
override suspend fun updateShow(showId: Long) { val localResult = localShowStore.getShow(showId)
val result1 = remoteSource1.getShow(showId) val result2 = remoteSource2.getShow(showId) val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. 1 2 3 -
override suspend fun updateShow(showId: Long) { val localResult = localShowStore.getShow(showId)
val result1 = remoteSource1.getShow(showId) val result2 = remoteSource2.getShow(showId) val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. -
override suspend fun updateShow(showId: Long) { val localResult = localShowStore.getShow(showId)
val result1 = remoteSource1.getShow(showId) val result2 = remoteSource2.getShow(showId) val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. 1 2 3 Runs in 1.2 seconds -
override suspend fun updateShow(showId: Long) { val localDeferred = async
{ localShowStore.getShow(showId) } val remoteDeferred1 = async { remoteSource1.getShow(showId) } val remoteDeferred2 = async { remoteSource2.getShow(showId) } val localResult = localDeferred.await() val result1 = remoteDeferred1.await() val result2 = remoteDeferred2.await() val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. -
override suspend fun updateShow(showId: Long) { val localDeferred = async
{ localShowStore.getShow(showId) } val remoteDeferred1 = async { remoteSource1.getShow(showId) } val remoteDeferred2 = async { remoteSource2.getShow(showId) } val localResult = localDeferred.await() val result1 = remoteDeferred1.await() val result2 = remoteDeferred2.await() val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. -
override suspend fun updateShow(showId: Long) { val localDeferred = async
{ localShowStore.getShow(showId) } val remoteDeferred1 = async { remoteSource1.getShow(showId) } val remoteDeferred2 = async { remoteSource2.getShow(showId) } val localResult = localDeferred.await() val result1 = remoteDeferred1.await() val result2 = remoteDeferred2.await() val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. -
override suspend fun updateShow(showId: Long) { val localDeferred = async
{ localShowStore.getShow(showId) } val remoteDeferred1 = async { remoteSource1.getShow(showId) } val remoteDeferred2 = async { remoteSource2.getShow(showId) } val localResult = localDeferred.await() val result1 = remoteDeferred1.await() val result2 = remoteDeferred2.await() val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. -
override suspend fun updateShow(showId: Long) { val localDeferred = async
{ localShowStore.getShow(showId) } val remoteDeferred1 = async { remoteSource1.getShow(showId) } val remoteDeferred2 = async { remoteSource2.getShow(showId) } val localResult = localDeferred.await() val result1 = remoteDeferred1.await() val result2 = remoteDeferred2.await() val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. -
override suspend fun updateShow(showId: Long) { val localDeferred = async
{ localShowStore.getShow(showId) } val remoteDeferred1 = async { remoteSource1.getShow(showId) } val remoteDeferred2 = async { remoteSource2.getShow(showId) } val localResult = localDeferred.await() val result1 = remoteDeferred1.await() val result2 = remoteDeferred2.await() val merged = mergeShow(localResult, result1, result2) localShowStore.saveShow(merged) }. Runs in 0.8 second -
class ShowDetailsViewModel: ViewModel() { val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> init { refresh() } private fun refresh() { launch { showRepository.updateShow(showId) // update view state } } } -
class ShowDetailsViewModel: ViewModel() { val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> init { refresh() } private fun refresh() { launch { showRepository.updateShow(showId) // update view state } } } -
class ShowDetailsViewModel: ViewModel() { val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> init { refresh() } private fun refresh() { launch { showRepository.updateShow(showId) // update view state } } } -
class ShowDetailsViewModel: ViewModel() { val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> init { refresh() } private fun refresh() { launch { showRepository.updateShow(showId) // update view state } } } -
class ShowDetailsViewModel: ViewModel() { val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> init {• refresh() }. private fun refresh() {• launch {• showRepository.updateShow(showId) // update view state }. }. }. -
class ShowDetailsViewModel: ViewModel() { private fun refresh() { launch {
showRepository.updateShow(showId) // update view state }. }. }. -
class ShowDetailsViewModel: ViewModel() { private fun refresh() { val job
= launch { showRepository.updateShow(showId) // update view state }. }. }. -
class ShowDetailsViewModel: ViewModel() { private fun refresh() { val job
= launch { showRepository.updateShow(showId) // update view state }. // can call job.cancel() }. }. -
class ShowDetailsViewModel: ViewModel() { private var updateShowJob: Job? = null
private fun refresh() { val job = launch { showRepository.updateShow(showId) // update view state }. // can call job.cancel() }. }. -
class ShowDetailsViewModel: ViewModel() { private var updateShowJob: Job? = null
private fun refresh() { updateShowJob = launch { showRepository.updateShow(showId) // update view state }. // can call job.cancel() }. }. -
class ShowDetailsViewModel: ViewModel() { private var updateShowJob: Job? = null
private fun refresh() { updateShowJob = launch { showRepository.updateShow(showId) // update view state }. }. }. -
class ShowDetailsViewModel: ViewModel() { private var updateShowJob: Job? = null
private fun refresh() { updateShowJob = launch { showRepository.updateShow(showId) // update view state }. }. override fun onCleared() { updateShowJob ?.cancel() } }. -
class ShowDetailsViewModel: ViewModel() { private var updateShowJob: Job? = null
private var updateEpisodesJob: Job? = null private fun refresh() { updateShowJob = launch { showRepository.updateShow(showId) // update view state }. updateShowJob = launch { ... } }. override fun onCleared() { updateShowJob ?.cancel() updateEpisodesJob ?.cancel() } }. -
class ShowDetailsViewModel: ViewModel() { private var updateShowJob: Job? = null
private var updateEpisodesJob: Job? = null private var updateCastJob: Job? = null private fun refresh() { updateShowJob = launch { showRepository.updateShow(showId) // update view state }. updateShowJob = launch { ... } updateCastJob = launch { ... } }. override fun onCleared() { updateShowJob ?.cancel() updateEpisodesJob ?.cancel() updateCastJob ?.cancel() } }. -
class ShowDetailsViewModel: ViewModel() { val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> private val job = Job() init {• refresh() }. private fun refresh() {• launch(parent = job) {• showRepository.updateShow(showId) // update view state }. }. -
class ShowDetailsViewModel: ViewModel() { val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> private val job = Job() init { refresh() }. private fun refresh() { launch(parent = job) { showRepository.updateShow(showId) // update view state }. }. override onCleared() { -
private val job = Job() init { refresh() }. private
fun refresh() { launch(parent = job) { showRepository.updateShow(showId) // update view state }. }. override onCleared() { job.cancel() } .. }. -
private val job = Job() init { refresh() }. private
fun refresh() { launch(parent = job) { showRepository.updateShow(showId) // update view state }. }. override onCleared() { job.cancel() } } .. -
private val job = Job() init { refresh() }. private
fun refresh() { launch(parent = job) { showRepository.updateShow(showId) // update view state }. }. override onCleared() { job.cancel() } } .. -
private val job = Job() init { refresh() }. private
fun refresh() { launch(parent = job) { showRepository.updateShow(showId) // update view state }. }. override onCleared() { job.cancel() } } .. launch is now scoped to the lifetime of the ViewModel -
private val job = Job() init { refresh() }. private
fun refresh() { launch(parent = job) { showRepository.updateShow(showId) // update view state }. }. override onCleared() { super.onCleared() job.cancel() } } .. Explicit -
launch(parent = job) { } suspend fun updateShow(showId: Long) {
val local = async { localShowStore.getShow(showId) }} val remote = async { remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) }. -
launch(parent = job) { } suspend fun updateShow(showId: Long) {
val local = async { localShowStore.getShow(showId) }} val remote = async { remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) }. New coroutines No parent Suspended job.cancel() Cancelled -
init { refresh() }. private fun refresh() { launch(parent =
job) { showRepository.updateShow(showId) // update view state }. }. override onCleared() { Deprecated in v0.26 async too -
New! v0.26 CoroutineScope async & launch become instance methods Allows
objects to provide scope for coroutines You provide a default context -
class ShowDetailsViewModel: ViewModel() {• val showRepository: ShowRepository = // ...
val state: LiveData<ViewState> private val job = Job() init { refresh() }. private fun refresh() {• launch(parent = job) {• showRepository.updateShow(showId) // update view state }. }. override onCleared() { -
class ShowDetailsViewModel: ViewModel(), CoroutineScope {• val showRepository: ShowRepository = //
... val state: LiveData<ViewState> private val job = Job() init { refresh() }. private fun refresh() {• launch(parent = job) {• showRepository.updateShow(showId) // update view state }. }. override onCleared() { -
class ShowDetailsViewModel: ViewModel(), CoroutineScope {• val showRepository: ShowRepository = //
... val state: LiveData<ViewState> private val job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main init { refresh() }. private fun refresh() {• launch(parent = job) {• showRepository.updateShow(showId) // update view state }. -
override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main init
{ refresh() }. private fun refresh() {• launch(parent = job) {• showRepository.updateShow(showId) // update view state }. }. override onCleared() { super.onCleared() job.cancel() }. }. -
override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main init
{ refresh() }. private fun refresh() {• launch {• showRepository.updateShow(showId) // update view state }. }. override onCleared() {• super.onCleared() job.cancel() }. }. -
override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main init
{ refresh() }. private fun refresh() {• this.launch(context = coroutineContext) {• showRepository.updateShow(showId) // update view state }. }. override onCleared() {• super.onCleared() job.cancel() }. }. -
open class ScopedViewModel : ViewModel(), CoroutineScope { private val job
= Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main override fun onCleared() { super.onCleared() job.cancel() } } -
launch { } suspend fun updateShow(showId: Long) {} val local
= async {} localShowStore.getShow(showId) }} val remote = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) }. -
launch { } suspend fun updateShow(showId: Long) = coroutineScope {}
val local = async {} localShowStore.getShow(showId) }} val remote = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) }. -
launch { } suspend fun updateShow(showId: Long) = coroutineScope {}
val local = async {} localShowStore.getShow(showId) }} val remote = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) }. Child coroutines Suspended job.cancel() Cancelled Children are cancelled too -
open class ScopedFragment : Fragment(), CoroutineScope { private val job
= Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main override fun onDestroy() { super.onDestroy() job.cancel() } } -
// In your Activity / Fragment val observer = MyObserver()
getLifecycle().addObserver(observer) class MyObserver : DefaultLifecycleObserver {{ override fun onCreate(owner: LifecycleOwner) {{ // we’re created }- override fun onDestroy(owner: LifecycleOwner) {{ // we’re destroyed }) }{ -
class MyObserver : DefaultLifecycleObserver {{ override fun onCreate(owner: LifecycleOwner) {{
// we’re created }- override fun onDestroy(owner: LifecycleOwner) {{ // we’re destroyed }) }{ // In your Activity / Fragment val observer = MyObserver() getLifecycle().addObserver(observer) -
class LifecycleScope : DefaultLifecycleObserver {{ override fun onDestroy(owner: LifecycleOwner) {{
// we’re destroyed }) }{ -
class LifecycleScope : DefaultLifecycleObserver {{ val job = Job(){ override
fun onDestroy(owner: LifecycleOwner) {{ // we’re destroyed }) }{ -
class LifecycleScope : DefaultLifecycleObserver {{ val job = Job() override
fun onDestroy(owner: LifecycleOwner) { // we’re destroyed{ job.cancel() }) }{ -
class LifecycleScope : DefaultLifecycleObserver, CoroutineScope {{ val job = Job()
override fun onDestroy(owner: LifecycleOwner) { // we’re destroyed{ job.cancel() }) }{ -
class LifecycleScope : DefaultLifecycleObserver, CoroutineScope {{ val job = Job()
override val coroutineContext = job + Dispatchers.Main override fun onDestroy(owner: LifecycleOwner) { // we’re destroyed{ job.cancel() }) }{ class DetailsFragment : Fragment() { private val scope = LifecycleScope() init { lifecycle.addObserver(scope) }} -
class DetailsFragment : Fragment() { private val scope = LifecycleScope()
init { lifecycle.addObserver(scope) }} override fun onCreateView( ...) { // ... }} }} // we’re destroyed{ job.cancel() }) }{ -
class DetailsFragment : Fragment() { private val scope = LifecycleScope()
init { lifecycle.addObserver(scope) }} override fun onCreateView( ...) { // ... }} }} -
class DetailsFragment : Fragment() { private val scope = LifecycleScope()
init { lifecycle.addObserver(scope) }} override fun onStart() { scope.launch { // something async } } override fun onCreateView( ...) { // ... }} }} -
class DetailsFragment : Fragment() { private val scope = LifecycleScope()
init { lifecycle.addObserver(scope) }} override fun onStart() { scope.launch { // something async } } override fun onCreateView( ...) { // ... }} }} Scoped to Fragment lifecycle -
Call a suspending function Check isActive if (job != null
&& !job.isActive) { throw job.getCancellationException() } Two ways to co-operate yield() -
Two ways to co-operate Call a suspending function Check isActive
launch { files.forEach { file -> if (isActive) doSomethingWith(file) } } -
suspend fun updateShow(showId: Long) = coroutineScope {} val local =
async {} localShowStore.getShow(showId) }} val remote = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) }} -
suspend fun updateShow(showId: Long) = coroutineScope {} val local =
async {} localShowStore.getShow(showId) }} val trakt = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) // throws CrashyMcCrashfaceException() }} -
suspend fun updateShow(showId: Long) = coroutineScope {} val local =
async {} localShowStore.getShow(showId) }} val trakt = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) // throws CrashyMcCrashfaceException() }} Treated like an uncaught exception -
suspend fun updateShow(showId: Long) = coroutineScope {} val local =
async {} localShowStore.getShow(showId) }} val remote = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) }} -
suspend fun updateShow(showId: Long) = coroutineScope {} val local =
async {} localShowStore.getShow(showId) // throws CrashyMcCrashfaceException() }} val remote = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await())} localShowStore.saveShow(merged)} }} -
suspend fun updateShow(showId: Long) = coroutineScope {} val local =
async {} localShowStore.getShow(showId) // throws CrashyMcCrashfaceException() }} val remote = async {} remoteSource.getShow(showId) }} val merged = mergeShow(local.await(), remote.await())} localShowStore.saveShow(merged)} }} Thrown here -
suspend fun updateShow(showId: Long) = coroutineScope {} val local =
async {} localShowStore.getShow(showId) // throws CrashyMcCrashfaceException() }} val remote = async {} remoteSource.getShow(showId) }} try {} val merged = mergeShow(local.await(), remote.await()) localShowStore.saveShow(merged) } catch (t: Throwable) {} // Handle the exception }} }} -
DefaultScheduler New! v0.30 Elastic thread executor Uses cpuCount threads (core)
Now set as Dispatchers.Default in 0.30 -
New! v0.25 IO Designed for blocking I/O tasks Uses 64
<= cpuCount threads launch(IO) {{ // network things }} -
New! v0.25 async { val local = withContext(IO) { fileStore.loadImage(
...) }} // No thread context switch! return processImage(local) }} Shares threads IO dispatcher uses DefaultScheduler IO -
async { val local = withContext(IO) { fileStore.loadImage( ...) }}
// No thread context switch! return processImage(local) }} Shares threads IO dispatcher uses DefaultScheduler New! v0.25 IO -
async { val local = withContext(IO) { fileStore.loadImage(...) }} //
No thread context switch! return processImage(local) }} Shares threads IO dispatcher uses DefaultScheduler New! v0.25 IO -
End up mainly using Single, Maybe & Completable Only exist
in RxJava RxScala RxGroovy -
val show = withContext(dispatchers.io) {} service.trendingShows().await() }} interface RemoteService {}
@GET("/trendingshows") fun trendingShows(): Single<List<Show>> }} -
val show = withContext(dispatchers.io) {} service.trendingShows().await() }} interface RemoteService {}
@GET("/trendingshows") fun trendingShows(): Single<List<Show>> }} -
interface RemoteService {} @GET("/trendingshows") suspend fun trendingShows(): List<Show> }} val
show = withContext(dispatchers.io) {} service.trendingShows().await() }} -
interface RemoteService {} @GET("/trendingshows") suspend fun trendingShows(): List<Show> }} val
show = withContext(dispatchers.io) {} service.trendingShows().await() }} Coming to Retrofit soon™ -
interface RemoteService {} @GET("/trendingshows") suspend fun trendingShows(): List<Show> }} val
show = withContext(dispatchers.io) {} service.trendingShows().await() }} -
interface RemoteService {} @GET("/trendingshows") suspend fun trendingShows(): List<Show> }} val
show = withContext(dispatchers.io) {} service.trendingShows() }} -
val channel = Channel<Bitmap>() launch { // First coroutine to
load images files.forEach { file -> val bitmap = loadBitmap(file) channel.send(bitmap) } // We're done with the channel channel.close() } launch { // Second coroutine to process them -
val channel = Channel<Bitmap>() launch { // First coroutine to
load images files.forEach { file -> val bitmap = loadBitmap(file) channel.send(bitmap) } // We're done with the channel channel.close() } launch { // Second coroutine to process them -
val channel = Channel<Bitmap>() launch { // First coroutine to
load images files.forEach { file -> val bitmap = loadBitmap(file) channel.send(bitmap) } // We're done with the channel channel.close() } launch { // Second coroutine to process them -
val channel = Channel<Bitmap>() launch { // First coroutine to
load images files.forEach { file -> val bitmap = loadBitmap(file) channel.send(bitmap) } // We're done with the channel channel.close() } launch { // Second coroutine to process them -
files.forEach { file -> val bitmap = loadBitmap(file) channel.send(bitmap) }
// We're done with the channel channel.close() } launch { // Second coroutine to process them channel.consumeEach { bitmap -> processBitmap(bitmap) } } -
all any associate associateBy associateByTo associateTo consume consumeEach consumeEachIndexed consumes
count distinct distinctBy drop dropWhile elementAt elementAtOrElse elementAtOrNull filter filterIndexed filterIndexedTo filterNot filterNotNull filterNotNullTo filterNotTo filterTo find findLast first firstOrNull flatMap fold foldIndexed groupBy groupByTo indexOf indexOfFirst indexOfLast last l a s t I n d e x O f l a s t O r N u l l m a p m a p I n d e x e d mapIndexedNotNull mapIndexedNotNullTo mapIndexedTo mapNotNull mapNotNullTo mapTo maxBy maxWith minBy minWith none partition reduce reduceIndexed requireNoNulls single singleOrNull sumBy sumByDouble take takeWhile toChannel toCollection toList toMap toMutableList toMutableSet toSet withIndex zip Channels has 73 built-in operators -
aggregate all amb ambWith and apply asObservable asyncAction asyncFunc averageDouble
length limit longCount map mapMany materialize max maxBy merge mergeDelayError Compare that to RxJava 230ish -
Operators are easier to write in coroutines fun <T, R>
Publisher<T>.map( context: CoroutineContext, mapper: (T) -> R ) = GlobalScope.publish(context) { consumeEach { send(mapper(it)) } } -
Get last known location FusedLocationProviderClient client.getLastLocation().addOnCompleteListener { task -> //
where am i? val location = task.result } Location In Google Play Services -
suspendCoroutine { ... } Given a continuation to later resume
Will run the lambda and then immediately suspend How you pass the result back -
Get last known location suspend fun getLastLocation(): Location { return
suspendCoroutine { continuation -> }} }} // TODO -
Get last known location suspend fun getLastLocation(): Location { return
suspendCoroutine { continuation -> }} }} -
Get last known location suspend fun getLastLocation(): Location { return
suspendCoroutine { continuation -> locationClient.lastLocation.addOnCompleteListener { task -> continuation.resume(task.result) }} }} }} -
Get last known location suspend fun getLastLocation(): Location { return
suspendCoroutine { continuation -> locationClient.lastLocation.addOnCompleteListener { task -> continuation.resume(task.result) }} }} }} Resumes coroutine with result -
Get last known location suspend fun getLastLocation(): Location { return
suspendCoroutine { continuation -> locationClient.lastLocation.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(task.result) } else { continuation.resumeWithException(task.exception !!) } }} }} }} -
FusedLocationProviderClient Takes a callback parameter fun requestLocationUpdates( request: LocationRequest, callback:
LocationCallback, looper: Looper ): Task<Void> -
fun removeLocationUpdates( callback: LocationCallback ): Task<Void> Remove the callback when
done request: LocationRequest, callback: LocationCallback, looper: Looper ): Task<Void> -
fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> {} val channel =
Channel<Location>() // TODO update channel return channel }} -
fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> {} val channel =
Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { channel.sendBlocking(result.getLastLocation()) }} }} // TODO request location updates return channel }} -
fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel =
Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { channel.sendBlocking(result.getLastLocation()) } } // TODO request location updates return channel } -
fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel =
Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { channel.sendBlocking(result.getLastLocation()) }} }} // TODO request location updates return channel }} -
fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel =
Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { channel.sendBlocking(result.getLastLocation()) }} }} return channel }} -
fun observeLocation( locationRequest: LocationRequest ): ReceiveChannel<Location> { val channel =
Channel<Location>() val callback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { channel.sendBlocking(result.getLastLocation()) }} }} // Start location updates, sending locations to the // channel locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() )} -
val channel = Channel<Location>() val callback = object : LocationCallback()
{ override fun onLocationResult(result: LocationResult) { channel.sendBlocking(result.getLastLocation()) }} }} // Start location updates, sending locations to the // channel locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() )} return channel }} -
}} // Start location updates, sending locations to the //
channel locationClient.requestLocationUpdates( locationRequest, callback, Looper.myLooper() )} // Remove the location callback when the channel // is closed channel.invokeOnClose { locationClient.removeLocationUpdates(callback) } return channel }} -
lateinit var locationChannel: ReceiveChannel<Location> override fun onStart() { val locationRequest
= LocationRequest() .setSmallestDisplacement(100f) // 100m locationChannel = observeLocation(locationRequest) launch(Main) { locationChannel.consumeEach { // We have a new location! updateUiForLocation(it) } } } override fun onStop() { // Stop observing the location and -
lateinit var locationChannel: ReceiveChannel<Location> override fun onStart() { val locationRequest
= LocationRequest() .setSmallestDisplacement(100f) // 100m locationChannel = observeLocation(locationRequest) launch(Main) { locationChannel.consumeEach { // We have a new location! updateUiForLocation(it) } } } override fun onStop() { // Stop observing the location and -
lateinit var locationChannel: ReceiveChannel<Location> override fun onStart() { val locationRequest
= LocationRequest() .setSmallestDisplacement(100f) // 100m locationChannel = observeLocation(locationRequest) launch(Main) { locationChannel.consumeEach { // We have a new location! updateUiForLocation(it) } } } override fun onStop() { // Stop observing the location and -
lateinit var locationChannel: ReceiveChannel<Location> override fun onStart() { val locationRequest
= LocationRequest() .setSmallestDisplacement(100f) // 100m locationChannel = observeLocation(locationRequest) launch(Main) { locationChannel.consumeEach { // We have a new location! updateUiForLocation(it) }} }} }} override fun onStop() { // Stop observing the location and -
.setSmallestDisplacement(100f) // 100m locationChannel = observeLocation(locationRequest) launch(Main) { locationChannel.consumeEach {
// We have a new location! updateUiForLocation(it) }} }} }} override fun onStop() { // Stop observing the location and // close the channel locationChannel.cancel() }} -
.setSmallestDisplacement(100f) // 100m locationChannel = observeLocation(locationRequest) launch(Main) { locationChannel.consumeEach {
// We have a new location! updateUiForLocation(it) }} }} }} override fun onStop() { // Stop observing the location and // close the channel locationChannel.cancel() }} -
Exploring Coroutines in Kotlin Kotlin Coroutines in Practice Coroutines and
Reactive Programming - friends or foes? Effectenbeurzaal Tomorrow, 13:00 Effectenbeurzaal Tomorrow, 10:15 Granbeurszaal Tomorrow, 15:15