Share
Embed
Coroutine-First Android Architecture -- droidcon Lisbon
Coroutines allow us to write asynchronous code in an easy-to-read, declarative style. The structured concurrency pattern allows us to write this code without fear of leaks. But there’s much more to the coroutines API than suspend modifiers and CoroutineScopes, and with these new abilities should come new patterns.
In this talk, we’ll discuss the power behind structured concurrency and how we can use it to make our entire stack lifecycle-aware. We’ll see how we can use the tools coroutines give us to inform our application architecture, so that we can quickly write maintainable and testable features at a large scale.
Rick Busarow
September 09, 2019
Transcript
100 slides
-
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } Pre- Structured Concurrency -
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } Pre- Structured Concurrency -
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } Pre- Structured Concurrency -
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } Pre- Structured Concurrency -
@rbusarow Job hierarchy Job Job Job Job Job Job Job
Job Job Job Job -
Job @rbusarow Job hierarchy Explicit cancellation Job Job Job Job
Job Job Job Job Job Job Job Job Job -
Job @rbusarow Job hierarchy Explicit cancellation Job Job Job Job
Job Job Job Job Job Job .cancel() Job Job Job -
Job @rbusarow Job hierarchy Explicit cancellation Job Job Job Job
Job Job Job Job Job Job Job .cancel() -
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } Pre- Structured Concurrency -
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } Pre- Structured Concurrency Completely Autonomous -
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } 0.26 to 1.0 -
@rbusarow class SomeViewModel : ViewModel() { fun doSomething() { val
job = launch { … } } } fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() !-> Unit ): Job { … } 0.26 to 1.0 -
@rbusarow class SomeViewModel : ViewModel(), CoroutineScope { override val coroutineContext
= Job() + Dispatchers.Main fun doSomething() { val job = launch { … } } } Structured Concurrency -
@rbusarow class SomeViewModel : ViewModel(), CoroutineScope { override val coroutineContext
= Job() + Dispatchers.Main fun doSomething() { val job = launch { … } } override fun onCleared() { super.onCleared() coroutineContext.cancel() } } Structured Concurrency -
@rbusarow Androidx Lifecycle INITIALIZED STARTED RESUMED CREATED STARTED CREATED DESTROYED
viewModel init viewModel.onCleared() -
@rbusarow Androidx Lifecycle STARTED RESUMED CREATED Lifecycle B STARTED RESUMED
CREATED Lifecycle A -
@rbusarow Androidx Lifecycle STARTED RESUMED CREATED Lifecycle C STARTED RESUMED
CREATED Lifecycle B STARTED RESUMED CREATED Lifecycle A -
@rbusarow Androidx Lifecycle STARTED RESUMED CREATED Lifecycle C STARTED RESUMED
CREATED Lifecycle B STARTED RESUMED CREATED Lifecycle A …DESTROYED? ¯\_(ツ)_/¯ -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main val reminder = launch { while (true) { delay(1_000) Log.v("MainViewModel", "still alive! --> ${UUID.randomUUID()}") } } override fun onCleared() { super.onCleared() cancel() } } ViewModel lifecycle -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main val reminder = launch { while (true) { delay(1_000) Log.v("MainViewModel", "still alive! --> ${UUID.randomUUID()}") } } override fun onCleared() { super.onCleared() cancel() } } ViewModel lifecycle -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main val reminder = launch { while (true) { delay(1_000) Log.v("MainViewModel", "still alive! --> ${UUID.randomUUID()}") } } override fun onCleared() { super.onCleared() cancel() } } ViewModel lifecycle -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main val reminder = launch { while (true) { delay(1_000) Log.v("MainViewModel", "still alive! --> ${UUID.randomUUID()}") } } override fun onCleared() { super.onCleared() cancel() } } ViewModel lifecycle -
@rbusarow class MainViewModel : ViewModel() { val reminder = viewModelScope.launch
{ while (true) { delay(1_000) Log.v("MainViewModel", "still alive! --> ${UUID.randomUUID()}") } } } ViewModel lifecycle -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main } CoroutineContext -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main } CoroutineContext parent Job -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main } CoroutineContext parent Job default Dispatcher -
@rbusarow class MainViewModel : ViewModel(), CoroutineScope { override val coroutineContext:
CoroutineContext = SupervisorJob() + Dispatchers.Main } CoroutineContext interface CoroutineContext { val job: Job val continuationInterceptor: ContinuationInterceptor val coroutineExceptionHandler: CoroutineExceptionHandler val coroutineName: CoroutineName } -
@rbusarow fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart =
CoroutineStart.DEFAULT, block: suspend CoroutineScope.() !-> Unit ): Job { val newContext = newCoroutineContext(context) val coroutine = if (start.isLazy) LazyStandaloneCoroutine(newContext, block) else StandaloneCoroutine(newContext, active = true) coroutine.start(start, coroutine, block) return coroutine } CoroutineContext -
@rbusarow fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart =
CoroutineStart.DEFAULT, block: suspend CoroutineScope.() !-> Unit ): Job { val newContext = newCoroutineContext(context) val coroutine = if (start.isLazy) LazyStandaloneCoroutine(newContext, block) else StandaloneCoroutine(newContext, active = true) coroutine.start(start, coroutine, block) return coroutine } CoroutineContext -
@rbusarow fun CoroutineScope.newCoroutineContext( context: CoroutineContext ): CoroutineContext { val combined
= coroutineContext + context val debug = if (DEBUG) combined + CoroutineId(COROUTINE_ID.incrementAndGet()) else combined return if ( combined !!!== Dispatchers.Default !&& combined[ContinuationInterceptor] !== null ) debug + Dispatchers.Default else debug } CoroutineContext -
@rbusarow fun CoroutineScope.newCoroutineContext( context: CoroutineContext ): CoroutineContext { val combined
= coroutineContext + context val debug = if (DEBUG) combined + CoroutineId(COROUTINE_ID.incrementAndGet()) else combined return if ( combined !!!== Dispatchers.Default !&& combined[ContinuationInterceptor] !== null ) debug + Dispatchers.Default else debug } CoroutineContext -
@rbusarow public operator fun plus(context: CoroutineContext): CoroutineContext = if (context
=== EmptyCoroutineContext) this else // fast path -- avoid lambda creation context.fold(this) { acc, element -> val removed = acc.minusKey(element.key) if (removed === EmptyCoroutineContext) element else { // make sure interceptor is always last in the context (and thus is fast to get when present) val interceptor = removed[ContinuationInterceptor] if (interceptor == null) CombinedContext(removed, element) else { val left = removed.minusKey(ContinuationInterceptor) if (left === EmptyCoroutineContext) CombinedContext(element, interceptor) else CombinedContext(CombinedContext(left, element), interceptor) } } } CoroutineContext -
@rbusarow public operator fun plus(context: CoroutineContext): CoroutineContext = if (context
=== EmptyCoroutineContext) this else // fast path -- avoid lambda creation context.fold(this) { acc, element -> val removed = acc.minusKey(element.key) if (removed === EmptyCoroutineContext) element else { // make sure interceptor is always last in the context (and thus is fast to get when present) val interceptor = removed[ContinuationInterceptor] if (interceptor == null) CombinedContext(removed, element) else { val left = removed.minusKey(ContinuationInterceptor) if (left === EmptyCoroutineContext) CombinedContext(element, interceptor) else CombinedContext(CombinedContext(left, element), interceptor) } } } CoroutineContext -
@rbusarow object Dispatchers { val Default: CoroutineDispatcher val IO: CoroutineDispatcher
val Main: CoroutineDispatcher val Unconfined: CoroutineDispatcher } Dispatchers -
@rbusarow object Dispatchers { val Default: CoroutineDispatcher val IO: CoroutineDispatcher
val Main: CoroutineDispatcher val Unconfined: CoroutineDispatcher } Dispatchers CPU-bound -
@rbusarow object Dispatchers { val Default: CoroutineDispatcher val IO: CoroutineDispatcher
val Main: CoroutineDispatcher val Unconfined: CoroutineDispatcher } Dispatchers CPU-bound IO-bound -
@rbusarow object Dispatchers { val Default: CoroutineDispatcher val IO: CoroutineDispatcher
val Main: CoroutineDispatcher val Unconfined: CoroutineDispatcher } Dispatchers CPU-bound IO-bound UI -
@rbusarow object Dispatchers { val Default: CoroutineDispatcher val IO: CoroutineDispatcher
val Main: CoroutineDispatcher val Unconfined: CoroutineDispatcher } Dispatchers CPU-bound IO-bound UI Debugging -
@rbusarow object Dispatchers { val Default: CoroutineDispatcher val IO: CoroutineDispatcher
val Main: CoroutineDispatcher val Unconfined: CoroutineDispatcher } fun doSomething() = launch(Dispatchers.IO) { … } suspend fun doSomethingElse() = withContext(Dispatchers.Main) { … } Dispatchers -
@rbusarow object Dispatchers { val Default: CoroutineDispatcher val IO: CoroutineDispatcher
val Main: CoroutineDispatcher val Unconfined: CoroutineDispatcher } fun doSomething() = launch(Dispatchers.IO) { … } suspend fun doSomethingElse() = withContext(Dispatchers.Main) { … } Dispatchers Test CoroutineDispatcher? -
@rbusarow class SomeViewModel : ViewModel(), CoroutineScope { override val coroutineContext
= Job() + Dispatchers.Main fun doSomething() { val job = launch { … } } override fun onCleared() { super.onCleared() coroutineContext.cancel() } } CoroutineScope Injection -
@rbusarow class SomeViewModel(val coroutineScope: CoroutineScope) : ViewModel() { fun doSomething()
{ coroutineScope.launch { … } } override fun onCleared() { super.onCleared() coroutineScope.cancel() } } CoroutineScope Injection -
@rbusarow val myScope = object: CoroutineScope { override val coroutineContext
= Job() + Dispatchers.Main } val myOtherScope = object: CoroutineScope { override val coroutineContext = Job() + Dispatchers.Default } CoroutineScope Injection -
@rbusarow class MainCoroutineScope: CoroutineScope { override val coroutineContext = Job()
+ Dispatchers.Main } class DefaultCoroutineScope: CoroutineScope { override val coroutineContext = Job() + Dispatchers.Default } CoroutineScope Injection -
@rbusarow class MainCoroutineScopeImpl: MainCoroutineScope { override val coroutineContext = Job()
+ Dispatchers.Main } class DefaultCoroutineScopeImpl: DefaultCoroutineScope { override val coroutineContext = Job() + Dispatchers.Default } interface MainCoroutineScope: CoroutineScope interface DefaultCoroutineScope: CoroutineScope CoroutineScope Injection -
@rbusarow class SomeViewModel(val coroutineScope: CoroutineScope) : ViewModel() { fun doSomething()
{ coroutineScope.launch { … } } override fun onCleared() { super.onCleared() coroutineScope.cancel() } } CoroutineScope Injection -
@rbusarow class SomeViewModel(val coroutineScope: MainCoroutineScope) : ViewModel() { fun doSomething()
{ coroutineScope.launch { … } } override fun onCleared() { super.onCleared() coroutineScope.cancel() } } CoroutineScope Injection -
@rbusarow class MainCoroutineScopeImpl: MainCoroutineScope { override val coroutineContext = Job()
+ Dispatchers.Main } interface MainCoroutineScope: CoroutineScope class TestMainCoroutineScope: MainCoroutineScope { override val coroutineContext = Job() + TestCoroutineDispatcher() } CoroutineScope Injection -
@rbusarow fun doSomething() = launch(Dispatchers.IO) { … } suspend fun
doSomethingElse() = withContext(Dispatchers.Main) { … } CoroutineScope Injection -
@rbusarow interface DispatcherProvider { val default: CoroutineDispatcher val io: CoroutineDispatcher
val main: CoroutineDispatcher val mainImmediate: CoroutineDispatcher val unconfined: CoroutineDispatcher } DispatcherProvider -
@rbusarow interface DispatcherProvider : CoroutineContext.Element { override val key: CoroutineContext.Key<*>
get() = Key val default: CoroutineDispatcher val io: CoroutineDispatcher val main: CoroutineDispatcher val mainImmediate: CoroutineDispatcher val unconfined: CoroutineDispatcher companion object Key : CoroutineContext.Key<DispatcherProvider> } DispatcherProvider -
@rbusarow class MainCoroutineScope: CoroutineScope { override val coroutineContext = Job()
+ Dispatchers.Main } DispatcherProvider -
@rbusarow class MainCoroutineScopeImpl( dispatcherProvider: DispatcherProvider = DefaultDispatcherProvider() ): MainCoroutineScope =
MainCoroutineScope { override val coroutineContext = Job() + dispatcherProvider.main + dispatcherProvider } DispatcherProvider -
@rbusarow class MainCoroutineScopeImpl( dispatcherProvider: DispatcherProvider = DefaultDispatcherProvider() ): MainCoroutineScope =
MainCoroutineScope { override val coroutineContext = Job() + dispatcherProvider.main + dispatcherProvider } DispatcherProvider -
@rbusarow val CoroutineContext.dispatcherProvider: DispatcherProvider get() = get(DispatcherProvider) ?: DefaultDispatcherProvider() val
CoroutineScope.mainDispatcher: CoroutineDispatcher get() = dispatcherProvider.main DispatcherProvider -
@rbusarow val CoroutineContext.dispatcherProvider: DispatcherProvider get() = get(DispatcherProvider) ?: DefaultDispatcherProvider() val
CoroutineScope.mainDispatcher: CoroutineDispatcher get() = dispatcherProvider.main DispatcherProvider -
@rbusarow class SomeViewModel(val coroutineScope: MainCoroutineScope) : ViewModel() { fun doSomething()
{ coroutineScope.launch(Dispatchers.Main) { … } } override fun onCleared() { super.onCleared() coroutineScope.cancel() } } CoroutineScope Injection -
@rbusarow class SomeViewModel(val coroutineScope: MainCoroutineScope) : ViewModel() { fun doSomething()
{ coroutineScope.launch(coroutineScope.mainDispatcher) { … } } override fun onCleared() { super.onCleared() coroutineScope.cancel() } } CoroutineScope Injection -
@rbusarow class TestDispatcherProvider( override val default: TestCoroutineDispatcher = TestCoroutineDispatcher(), override
val io: TestCoroutineDispatcher = TestCoroutineDispatcher(), override val main: TestCoroutineDispatcher = TestCoroutineDispatcher(), override val mainImmediate: TestCoroutineDispatcher = TestCoroutineDispatcher(), override val unconfined: TestCoroutineDispatcher = TestCoroutineDispatcher() ) : DispatcherProvider TestDispatcherProvider -
@rbusarow class TestDispatcherProvider( override val default: TestCoroutineDispatcher = TestCoroutineDispatcher(), override
val io: TestCoroutineDispatcher = TestCoroutineDispatcher(), override val main: TestCoroutineDispatcher = TestCoroutineDispatcher(), override val mainImmediate: TestCoroutineDispatcher = TestCoroutineDispatcher(), override val unconfined: TestCoroutineDispatcher = TestCoroutineDispatcher() ) : DispatcherProvider fun TestDispatcherProvider(dispatcher: TestCoroutineDispatcher): TestDispatcherProvider = TestDispatcherProvider( default = dispatcher, io = dispatcher, main = dispatcher, mainImmediate = dispatcher, unconfined = dispatcher ) TestDispatcherProvider -
@rbusarow interface TestProvidedCoroutineScope : TestCoroutineScope, DefaultCoroutineScope, IOCoroutineScope, MainCoroutineScope, MainImmediateCoroutineScope, UnconfinedCoroutineScope
{ val dispatcherProvider: DispatcherProvider } TestDispatcherProvider -
@rbusarow class TestProvidedCoroutineScopeImpl( override val dispatcherProvider: DispatcherProvider, context: CoroutineContext =
EmptyCoroutineContext ) : TestProvidedCoroutineScope, TestCoroutineScope by TestCoroutineScope(context + dispatcherProvider) TestDispatcherProvider -
@rbusarow class TestProvidedCoroutineScopeImpl( override val dispatcherProvider: DispatcherProvider, context: CoroutineContext =
EmptyCoroutineContext ) : TestProvidedCoroutineScope, TestCoroutineScope by TestCoroutineScope(context + dispatcherProvider) fun TestProvidedCoroutineScope( dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher(), dispatcherProvider: TestDispatcherProvider = TestDispatcherProvider(dispatcher), context: CoroutineContext = EmptyCoroutineContext ): TestProvidedCoroutineScope = TestProvidedCoroutineScopeImpl( dispatcherProvider = dispatcherProvider, context = context + dispatcher ) TestDispatcherProvider -
@rbusarow class TestProvidedCoroutineScopeImpl( override val dispatcherProvider: DispatcherProvider, context: CoroutineContext =
EmptyCoroutineContext ) : TestProvidedCoroutineScope, TestCoroutineScope by TestCoroutineScope(context + dispatcherProvider) fun TestProvidedCoroutineScope( dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher(), dispatcherProvider: TestDispatcherProvider = TestDispatcherProvider(dispatcher), context: CoroutineContext = EmptyCoroutineContext ): TestProvidedCoroutineScope = TestProvidedCoroutineScopeImpl( dispatcherProvider = dispatcherProvider, context = context + dispatcher ) val myScope = TestProvidedCoroutineScope() TestDispatcherProvider -
@rbusarow class SomeViewModel(val coroutineScope: MainCoroutineScope) : ViewModel() { fun doSomething()
{ coroutineScope.launch(coroutineScope.mainDispatcher) { … } } override fun onCleared() { super.onCleared() coroutineScope.cancel() } } CoroutineScope Injection -
@rbusarow class SomeViewModel(val coroutineScope: MainCoroutineScope) : ViewModel() { fun doSomething()
{ coroutineScope.launch(coroutineScope.mainDispatcher) { … } } override fun onCleared() { super.onCleared() coroutineScope.cancel() } } CoroutineScope Injection -
@rbusarow class SomeRepository { suspend fun doSomething() = withContext(Dispatchers.IO) {
... } } CoroutineScope Injection -
@rbusarow class SomeRepository { suspend fun doSomething() = withContext(Dispatchers.IO) {
... } } val CoroutineContext.dispatcherProvider: DispatcherProvider get() = get(DispatcherProvider) ?: DefaultDispatcherProvider() CoroutineScope Injection -
@rbusarow class SomeRepository { suspend fun doSomething() = withContext(Dispatchers.IO) {
... } } val CoroutineContext.dispatcherProvider: DispatcherProvider get() = get(DispatcherProvider) ?: DefaultDispatcherProvider() suspend fun <T> withIO( context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T ): T { val newContext = coroutineContext.dispatcherProvider.io + context return withContext(newContext, block) } CoroutineScope Injection -
@rbusarow class SomeRepository { suspend fun doSomething() = withIO {
... } } val CoroutineContext.dispatcherProvider: DispatcherProvider get() = get(DispatcherProvider) ?: DefaultDispatcherProvider() suspend fun <T> withIO( context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T ): T { val newContext = coroutineContext.dispatcherProvider.io + context return withContext(newContext, block) } CoroutineScope Injection