Slide 1

Slide 1 text

Managing State Beyond ViewModels and Hilt September 15th, 2023 Ralf Wondratschek @vRallev | @[email protected] | @ralf_dev

Slide 2

Slide 2 text

Background

Slide 3

Slide 3 text

Background

Slide 4

Slide 4 text

Background

Slide 5

Slide 5 text

Background

Slide 6

Slide 6 text

https://www.youtube.com/watch?v=xESX82kwjn4

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

https://www.youtube.com/watch?v=0T_zvUEqsD4

Slide 9

Slide 9 text

Old architecture class Application

Slide 10

Slide 10 text

Old architecture class Application class AbcActivity class DefActivity

Slide 11

Slide 11 text

Old architecture class Application class GhiFragment class JklFragment class AbcActivity class DefActivity

Slide 12

Slide 12 text

Old architecture class Application class AbcViewModel class DefViewModel class GhiFragment class GhiViewModel class JklFragment class JklViewModel class AbcActivity class DefActivity

Slide 13

Slide 13 text

Old architecture - Bottlenecks

Slide 14

Slide 14 text

Old architecture - Bottlenecks ● Driven by Android and its window management and not by business logic ● Different lifecycles with different teardown hooks ● Custom lifecycles like user scope adjacent ● Coroutine scopes provided by Android components

Slide 15

Slide 15 text

Old architecture - Lifecycle Lifecycle managed by us Lifecycle managed by Android Business Logic UI rendering Activity Fragment ViewModel ViewModel flow: Flow operation() flow: Flow operation() Service objects

Slide 16

Slide 16 text

Old architecture - Lifecycle class RouteViewModel : ViewModel() { fun sendRequest() { viewModelScope.launch { httpClient.post(request) } } }

Slide 17

Slide 17 text

Old architecture - Lifecycle class RouteViewModel : ViewModel() { fun sendRequest() { viewModelScope.launch { httpClient.post(request) } } }

Slide 18

Slide 18 text

Old architecture - Lifecycle class Application : Context { open fun onCreate() = Unit } class Activity : Context { open fun onCreate(..) = Unit open fun onDestroy() = Unit } class Fragment { open fun onCreate(..) = Unit open fun onDestroy() = Unit } class ViewModel { open fun onCleared() = Unit }

Slide 19

Slide 19 text

Old architecture - Lifecycle interface Application.ActivityLifecycleCallbacks { ... } interface DefaultLifecycleObserver { ... }

Slide 20

Slide 20 text

Old architecture - Without unidirectional dataflow ● Challenges synchronizing multiple screens ● No holistic overview of the state of the application ● Way too easy to mix business logic with UI code ● Many services pushed into application scope

Slide 21

Slide 21 text

Old architecture - Without unidirectional dataflow Lifecycle managed by us Lifecycle managed by Android Business Logic UI rendering Activity Fragment ViewModel ViewModel flow: Flow operation() flow: Flow operation() Service objects

Slide 22

Slide 22 text

Old architecture - Without unidirectional dataflow ViewModel Activity operation1() operation2() operation3() flow1: Flow flow2: Flow flow3: Flow

Slide 23

Slide 23 text

Old architecture - Anti-pattern class AmazonApplication : Application() { @Inject lateinit var routingRepository: RoutingRepository @Inject lateinit var locationProvider: LocationProvider override fun onCreate() { super.onCreate() routingRepository.initialize() locationProvider.initialize() } }

Slide 24

Slide 24 text

Old architecture - Anti-pattern interface RoutingRepository { fun initialize() suspend fun loadRoute (): Route }

Slide 25

Slide 25 text

Old architecture - Anti-pattern class AmazonRoutingRepository @Inject constructor( @IODispatcher dispatcher: CoroutineDispatcher ) : RoutingRepository { private val coroutineScope = CoroutineScope(dispatcher) override fun initialize() { coroutineScope.launch { // Initialize } } override suspend fun loadRoute(): Route = ... }

Slide 26

Slide 26 text

Old architecture - Anti-pattern class AmazonRoutingRepository @Inject constructor( @IODispatcher dispatcher: CoroutineDispatcher ) : RoutingRepository { private val coroutineScope = CoroutineScope(dispatcher) override fun initialize() { coroutineScope.launch { // Initialize } } override suspend fun loadRoute(): Route = ... }

Slide 27

Slide 27 text

Old architecture - Anti-pattern class FakeRoutingRepository @Inject constructor() : RoutingRepository { override fun initialize() = Unit override suspend fun loadRoute(): Route = ... }

Slide 28

Slide 28 text

Old architecture - Hilt ● Strong coupling to Android components ● Custom components with limitations

Slide 29

Slide 29 text

Old architecture - Hilt

Slide 30

Slide 30 text

Goals

Slide 31

Slide 31 text

Goals ● Strongly decouple business logic from Android lifecycle ● Features are device agnostic ● Avoid thread and memory leaks

Slide 32

Slide 32 text

Design principles - Modular design

Slide 33

Slide 33 text

Design principles - Modular design class AmazonApplication : Application() { @Inject lateinit var routingRepository: RoutingRepository @Inject lateinit var locationProvider: LocationProvider override fun onCreate() { super.onCreate() routingRepository.initialize() locationProvider.initialize() } }

Slide 34

Slide 34 text

Design principles - Composition over inheritance

Slide 35

Slide 35 text

Design principles - Composition over inheritance AppCompatActivity BaseActivity InfoActivity ViewModel BaseViewModel InfoViewModel

Slide 36

Slide 36 text

Design principles - Dependency inversion by default

Slide 37

Slide 37 text

Design principles - Dependency inversion by default interface RoutingRepository { fun initialize() suspend fun loadRoute (): Route } class AmazonRoutingRepository @Inject constructor() : RoutingRepository { override fun initialize() = ... override suspend fun loadRoute(): Route = ... }

Slide 38

Slide 38 text

Design principles - Dependency inversion by default interface RoutingRepository { fun initialize() suspend fun loadRoute (): Route } class AmazonRoutingRepository @Inject constructor() : RoutingRepository { override fun initialize() = ... override suspend fun loadRoute(): Route = ... }

Slide 39

Slide 39 text

Design principles - Inject dependencies

Slide 40

Slide 40 text

Design principles - Inject dependencies class AmazonRoutingRepository @Inject constructor( @IODispatcher dispatcher: CoroutineDispatcher ) : RoutingRepository { private val coroutineScope = CoroutineScope(dispatcher) override fun initialize() { coroutineScope.launch { // Initialize } } override suspend fun loadRoute(): Route = ... }

Slide 41

Slide 41 text

Design principles - Inject dependencies class AmazonRoutingRepository @Inject constructor( @IODispatcher dispatcher: CoroutineDispatcher ) : RoutingRepository { private val coroutineScope = CoroutineScope(dispatcher) override fun initialize() { coroutineScope.launch { // Initialize } } override suspend fun loadRoute(): Route = ... }

Slide 42

Slide 42 text

Design principles - Unidirectional dataflow to drive UI

Slide 43

Slide 43 text

Design principles - Unidirectional dataflow to drive UI ViewModel Activity operation1() operation2() operation3() flow1: Flow flow2: Flow flow3: Flow

Slide 44

Slide 44 text

From Hilt to Anvil

Slide 45

Slide 45 text

From Hilt to Anvil https://www.droidcon.com/2022/06/28/dagger-anvil-learning-to-love-dependency-injection/

Slide 46

Slide 46 text

From Hilt to Anvil @Module @ContributesTo(AppScope::class) object RouteModule @Module @ContributesTo(AppScope::class, replaces = [RouteModule::class]) object TestRouteModule

Slide 47

Slide 47 text

From Hilt to Anvil interface RoutingRepository { suspend fun loadRoute (): Route } @ContributesBinding(scope = AppScope::class) class AmazonRoutingRepository @Inject constructor() : RoutingRepository { override suspend fun loadRoute(): Route = ... }

Slide 48

Slide 48 text

From Hilt to Anvil interface RoutingRepository { suspend fun loadRoute (): Route } @ContributesBinding(scope = AppScope::class) class AmazonRoutingRepository @Inject constructor() : RoutingRepository { override suspend fun loadRoute(): Route = ... }

Slide 49

Slide 49 text

From Hilt to Anvil @Module @InstallIn(ActivityComponent::class) @ContributesTo(ActivityScope::class) class RouteModule

Slide 50

Slide 50 text

From Hilt to Anvil class AmazonRoutingRepository @Inject constructor( @ApplicationContext context: Context application: Application ) : RoutingRepository

Slide 51

Slide 51 text

From Hilt to Anvil @Binds abstract fun bindRoutingRepository( repository: AmazonRoutingRepository ): RoutingRepository @ContributesBinding(AppScope::class) class AmazonRoutingRepository @Inject constructor( application: Application ) : RoutingRepository

Slide 52

Slide 52 text

From Hilt to Anvil class AmazonApplication : Application() { lateinit var component: AppComponent override fun onCreate() { super.onCreate() component = DaggerAppComponent.factory().create(applicationContext = this) component.inject(this) } }

Slide 53

Slide 53 text

From Hilt to Anvil class OpenSourceActivity : Activity() { private val viewModelFactory by viewModels() private val viewModel by viewModels { viewModelFactory } ... }

Slide 54

Slide 54 text

From Hilt to Anvil class ViewModelFactory( application: Application ) : ViewModelProvider.Factory, AndroidViewModel(application) { private val viewModels: Map, @JvmSuppressWildcards Provider> init { val component = application.component.createViewModelComponent() viewModels = component.viewModels() } override fun create(modelClass: Class): T { @Suppress("UNCHECKED_CAST") return viewModels.getValue(modelClass).get() as T } override fun onCleared() { // Clean up any resources } }

Slide 55

Slide 55 text

From Hilt to Anvil class ViewModelFactory( application: Application ) : ViewModelProvider.Factory, AndroidViewModel(application) { private val viewModels: Map, @JvmSuppressWildcards Provider> init { val component = application.component.createViewModelComponent() viewModels = component.viewModels() } override fun create(modelClass: Class): T { @Suppress("UNCHECKED_CAST") return viewModels.getValue(modelClass).get() as T } override fun onCleared() { // Clean up any resources } }

Slide 56

Slide 56 text

From Hilt to Anvil class ViewModelFactory( application: Application ) : ViewModelProvider.Factory, AndroidViewModel(application) { private val viewModels: Map, @JvmSuppressWildcards Provider> init { val component = application.component.createViewModelComponent() viewModels = component.viewModels() } override fun create(modelClass: Class): T { @Suppress("UNCHECKED_CAST") return viewModels.getValue(modelClass).get() as T } override fun onCleared() { // Clean up any resources } }

Slide 57

Slide 57 text

From Hilt to Anvil class ViewModelFactory( application: Application ) : ViewModelProvider.Factory, AndroidViewModel(application) { private val viewModels: Map, @JvmSuppressWildcards Provider> init { val component = application.component.createViewModelComponent() viewModels = component.viewModels() } override fun create(modelClass: Class): T { @Suppress("UNCHECKED_CAST") return viewModels.getValue(modelClass).get() as T } override fun onCleared() { // Clean up any resources } }

Slide 58

Slide 58 text

From Hilt to Anvil @ContributesMultibinding(ViewModelScope::class) @ViewModelKey(OpenSourceViewModel::class) class OpenSourceViewModel @Inject constructor( ... ) : ViewModel() { ... }

Slide 59

Slide 59 text

Scope

Slide 60

Slide 60 text

Scope “Scopes define the boundary software components operate in. A scope is a space with a well-defined lifecycle that can be created and torn down. Scopes host other objects and can bind them to their lifecycle. Sub-scopes or child scopes have the same or a shorter lifecycle as their parent scope.”

Slide 61

Slide 61 text

Scope “Scopes define the boundary software components operate in. A scope is a space with a well-defined lifecycle that can be created and torn down. Scopes host other objects and can bind them to their lifecycle. Sub-scopes or child scopes have the same or a shorter lifecycle as their parent scope.” – Ralf Wondratschek

Slide 62

Slide 62 text

Scope ● Android components as scope? ● Coroutine scopes? ● Dagger components as scope? ● Implement your own?

Slide 63

Slide 63 text

Scope interface Scope { val name: String val parent: Scope? fun buildChild(name: String, builder: (Builder.() -> Unit)? = null): Scope fun children(): Set fun register(scoped: Scoped) fun isDestroyed(): Boolean fun destroy() fun getService(key: String): T? } https://github.com/square/mortar/blob/master/mortar/src/main/java/mortar/MortarScope.java

Slide 64

Slide 64 text

Scope class Builder internal constructor( private val name: String, private val parent: Scope? ) { private val services = mutableMapOf() fun addService(key: String, service: Any) { services[key] = service } internal fun build(): Scope { return ScopeImpl(name, parent, services) } }

Slide 65

Slide 65 text

Scope - Services interface Scope { fun getService(key: String): T? } inline fun Scope.daggerComponent(): T { return ... } fun Scope.Builder.addDaggerComponent(component: Any) { addService(DAGGER_COMPONENT_KEY, component) }

Slide 66

Slide 66 text

Scope - Services interface Scope { fun getService(key: String): T? } inline fun Scope.daggerComponent(): T { return ... } fun Scope.Builder.addDaggerComponent(component: Any) { addService(DAGGER_COMPONENT_KEY, component) }

Slide 67

Slide 67 text

Scope - Services private const val COROUTINE_SCOPE_KEY = "coroutineScope" fun Scope.coroutineScope(context: CoroutineContext? = null): CoroutineScope { val result = checkNotNull(getService(COROUTINE_SCOPE_KEY)) { "Couldn't find CoroutineScopeScoped within scope $name." } check(result.isActive) { "Expected the coroutine scope ${result.coroutineContext[CoroutineName]?.name} " + "still to be active." } return result.createChild(context) } fun Scope.Builder.addCoroutineScope(coroutineScope: CoroutineScopeScoped) { addService(COROUTINE_SCOPE_KEY, coroutineScope) }

Slide 68

Slide 68 text

Scope - Services private const val COROUTINE_SCOPE_KEY = "coroutineScope" fun Scope.coroutineScope(context: CoroutineContext? = null): CoroutineScope { val result = checkNotNull(getService(COROUTINE_SCOPE_KEY)) { "Couldn't find CoroutineScopeScoped within scope $name." } check(result.isActive) { "Expected the coroutine scope ${result.coroutineContext[CoroutineName]?.name} " + "still to be active." } return result.createChild(context) } fun Scope.Builder.addCoroutineScope(coroutineScope: CoroutineScopeScoped) { addService(COROUTINE_SCOPE_KEY, coroutineScope) }

Slide 69

Slide 69 text

Scope - Services private const val COROUTINE_SCOPE_KEY = "coroutineScope" fun Scope.coroutineScope(context: CoroutineContext? = null): CoroutineScope { val result = checkNotNull(getService(COROUTINE_SCOPE_KEY)) { "Couldn't find CoroutineScopeScoped within scope $name." } check(result.isActive) { "Expected the coroutine scope ${result.coroutineContext[CoroutineName]?.name} " + "still to be active." } return result.createChild(context) } fun Scope.Builder.addCoroutineScope(coroutineScope: CoroutineScopeScoped) { addService(COROUTINE_SCOPE_KEY, coroutineScope) }

Slide 70

Slide 70 text

Scope - Services rootScope = Scope.buildRootScope { addDaggerComponent(createDaggerComponent()) } application.rootScope .buildChild(name = this::class.java.simpleName) { addDaggerComponent( application.rootScope .daggerComponent() .createActivityComponent() ) }

Slide 71

Slide 71 text

Scope - Hierarchy AppScope

Slide 72

Slide 72 text

Scope - Hierarchy AppScope UserScope LoggedOutScope ActivityScope

Slide 73

Slide 73 text

Scope - Hierarchy in reality AppScope UserScope ActivityScope ViewModelScope

Slide 74

Slide 74 text

Scope - Callback interface Scope { fun register(scoped: Scoped) }

Slide 75

Slide 75 text

Scope - Callback interface Scope { fun register(scoped: Scoped) } interface Scoped { fun onEnterScope(scope: Scope) = Unit fun onExitScope() = Unit }

Slide 76

Slide 76 text

Scope - Callback interface RoutingRepository { fun initialize() suspend fun loadRoute (): Route } class AmazonRoutingRepository : RoutingRepository { override fun initialize() = ... override suspend fun loadRoute(): Route = ... }

Slide 77

Slide 77 text

Scope - Callback interface RoutingRepository { suspend fun loadRoute (): Route } class AmazonRoutingRepository : RoutingRepository, Scoped { override fun onEnterScope(scope: Scope) { scope.coroutineScope().launch { ... } } override suspend fun loadRoute(): Route = ... }

Slide 78

Slide 78 text

Scope - Callback interface RoutingRepository { suspend fun loadRoute (): Route } class AmazonRoutingRepository : RoutingRepository, Scoped { override fun onEnterScope(scope: Scope) { scope.coroutineScope().launch { ... } } override suspend fun loadRoute(): Route = ... }

Slide 79

Slide 79 text

Scope - Callback interface RoutingRepository { suspend fun loadRoute (): Route } class AmazonRoutingRepository : RoutingRepository, Scoped { override fun onEnterScope(scope: Scope) { scope.coroutineScope().launch { ... } } override suspend fun loadRoute(): Route = ... }

Slide 80

Slide 80 text

Scope - Callback interface RoutingRepository { suspend fun loadRoute (): Route } @ContributesMultibindingScoped(AppScope::class) class AmazonRoutingRepository : RoutingRepository, Scoped { override fun onEnterScope(scope: Scope) { scope.coroutineScope().launch { ... } } override suspend fun loadRoute(): Route = ... }

Slide 81

Slide 81 text

Scope - Callback interface RoutingRepository { suspend fun loadRoute (): Route } @ContributesMultibindingScoped(AppScope::class) class AmazonRoutingRepository : RoutingRepository, Scoped { override fun onEnterScope(scope: Scope) { scope.coroutineScope().launch { ... } } override suspend fun loadRoute(): Route = ... }

Slide 82

Slide 82 text

Scope - Callback @ContributesTo(AppScope::class) interface Component { @ForScope(AppScope::class) fun appScopedInstances(): Set } rootScope = Scope.buildRootScope { addDaggerComponent(createDaggerComponent()) } rootScope.register(rootScope.daggerComponent().appScopedInstances())

Slide 83

Slide 83 text

Scope - Callback @SingleIn(AppScope::class) @ContributesMultibindingScoped(AppScope::class) class ActivityListener @Inject constructor( private val application: Application ) : Scoped { val startedActivities: StateFlow> = ... private val listener = object : Application.ActivityLifecycleCallbacks { ... } override fun onEnterScope(scope: Scope) { application.registerActivityLifecycleCallbacks(listener) } override fun onExitScope() { application.unregisterActivityLifecycleCallbacks(listener) } }

Slide 84

Slide 84 text

Scope - Callback @SingleIn(AppScope::class) @ContributesMultibindingScoped(AppScope::class) class ActivityListener @Inject constructor( private val application: Application ) : Scoped { val startedActivities: StateFlow> = ... private val listener = object : Application.ActivityLifecycleCallbacks { ... } override fun onEnterScope(scope: Scope) { application.registerActivityLifecycleCallbacks(listener) } override fun onExitScope() { application.unregisterActivityLifecycleCallbacks(listener) } }

Slide 85

Slide 85 text

Scope - Callback @SingleIn(AppScope::class) @ContributesMultibindingScoped(AppScope::class) class ActivityListener @Inject constructor( private val application: Application ) : Scoped { val startedActivities: StateFlow> = ... private val listener = object : Application.ActivityLifecycleCallbacks { ... } override fun onEnterScope(scope: Scope) { application.registerActivityLifecycleCallbacks(listener) } override fun onExitScope() { application.unregisterActivityLifecycleCallbacks(listener) } }

Slide 86

Slide 86 text

Scope - Callback @SingleIn(AppScope::class) @ContributesMultibindingScoped(AppScope::class) class QeCommandReceiver @Inject constructor( private val application: Application, ) : BroadcastReceiver(), Scoped { override fun onEnterScope(scope: Scope) { application.registerReceiver(this, IntentFilter("...")) } override fun onExitScope() { application.unregisterReceiver(this) } override fun onReceive(context: Context, intent: Intent) { when (intent.getStringExtra("cmd")) { ... } } }

Slide 87

Slide 87 text

Scope - Callback @SingleIn(AppScope::class) @ContributesMultibindingScoped(AppScope::class) class QeCommandReceiver @Inject constructor( private val application: Application, ) : BroadcastReceiver(), Scoped { override fun onEnterScope(scope: Scope) { application.registerReceiver(this, IntentFilter("...")) } override fun onExitScope() { application.unregisterReceiver(this) } override fun onReceive(context: Context, intent: Intent) { when (intent.getStringExtra("cmd")) { ... } } }

Slide 88

Slide 88 text

Scope - Callback @SingleIn(AppScope::class) @ContributesMultibindingScoped(AppScope::class) class QeCommandReceiver @Inject constructor( private val application: Application, ) : BroadcastReceiver(), Scoped { override fun onEnterScope(scope: Scope) { application.registerReceiver(this, IntentFilter("...")) } override fun onExitScope() { application.unregisterReceiver(this) } override fun onReceive(context: Context, intent: Intent) { when (intent.getStringExtra("cmd")) { ... } } }

Slide 89

Slide 89 text

Scope - Callback @SingleIn(AppScope::class) @ContributesMultibindingScoped(AppScope::class) class QeCommandReceiver @Inject constructor( private val application: Application, ) : BroadcastReceiver(), Scoped { override fun onEnterScope(scope: Scope) { application.registerReceiver(this, IntentFilter("...")) } override fun onExitScope() { application.unregisterReceiver(this) } override fun onReceive(context: Context, intent: Intent) { when (intent.getStringExtra("cmd")) { ... } } }

Slide 90

Slide 90 text

Scope - Constructor? If a class part of DriverSessionScope implements Scoped and injects DriverSessionService (which is app-scoped), then we end up in a livelock and the app freezes. There is nothing wrong with this setup and it should be supported. The chain of events is as follows: the app scope gets created and someone injects DriverSessionService. Dagger attempts to create DriverSessionService. In the constructor the service immediately creates the DriverSessionScope, when the driver is already logged in. As part of this routine the service injects all Scoped instances contributed to the DriverSessionScope. If one of these instances injects DriverSessionService (again, from the app scope and that's valid), then Dagger cannot provide the DriverSessionService, because the previous instance hasn't been created yet and is still in the constructor call. Therefore, Dagger creates another DriverSessionService and the whole loop repeats. TL;DR: Don't run any logic in the constructor. The solution is implementing Scoped and moving all logic from the constructor call into onEnterScope().

Slide 91

Slide 91 text

Scope - Constructor? If a class part of DriverSessionScope implements Scoped and injects DriverSessionService (which is app-scoped), then we end up in a livelock and the app freezes. There is nothing wrong with this setup and it should be supported. The chain of events is as follows: the app scope gets created and someone injects DriverSessionService. Dagger attempts to create DriverSessionService. In the constructor the service immediately creates the DriverSessionScope, when the driver is already logged in. As part of this routine the service injects all Scoped instances contributed to the DriverSessionScope. If one of these instances injects DriverSessionService (again, from the app scope and that's valid), then Dagger cannot provide the DriverSessionService, because the previous instance hasn't been created yet and is still in the constructor call. Therefore, Dagger creates another DriverSessionService and the whole loop repeats. TL;DR: Don't run any logic in the constructor. The solution is implementing Scoped and moving all logic from the constructor call into onEnterScope().

Slide 92

Slide 92 text

Scope - Tests @Test fun `test routing repository registers for push updates`() { val repository = AmazonRoutingRepository() repository.onEnterScope(Scope.buildTestScope()) ... }

Slide 93

Slide 93 text

Scope - Tests fun Scope.Companion.buildTestScope( name: String = "test", context: CoroutineContext? = null, builder: (Scope.Builder.() -> Unit)? = null ): Scope { var coroutineContext = SupervisorJob() + UnconfinedTestDispatcher() + CoroutineName(name) if (context != null) { coroutineContext += context } val coroutineScope = CoroutineScopeScoped(coroutineContext) val scope = buildRootScope(name = name) { addCoroutineScopeScoped(coroutineScope) builder?.invoke(this) } scope.register(coroutineScope) return scope }

Slide 94

Slide 94 text

Scope - Recap

Slide 95

Slide 95 text

Scope - Recap class RouteViewModel : ViewModel() { fun sendRequest() { viewModelScope.launch { httpClient.post(request) } } }

Slide 96

Slide 96 text

Scope - Recap class RouteViewModel : ViewModel() { fun sendRequest() { viewModelScope.launch { httpClient.post(request) } } }

Slide 97

Slide 97 text

Scope - Recap class Application : Context { open fun onCreate() = Unit } class Activity : Context { open fun onCreate(..) = Unit open fun onDestroy() = Unit } class Fragment { open fun onCreate(..) = Unit open fun onDestroy() = Unit } class ViewModel { open fun onCleared() = Unit }

Slide 98

Slide 98 text

Scope - Recap class Application : Context { open fun onCreate() = Unit } class Activity : Context { open fun onCreate(..) = Unit open fun onDestroy() = Unit } class Fragment { open fun onCreate(..) = Unit open fun onDestroy() = Unit } class ViewModel { open fun onCleared() = Unit }

Slide 99

Slide 99 text

Scope - Recap class AmazonApplication : Application() { @Inject lateinit var routingRepository: RoutingRepository @Inject lateinit var locationProvider: LocationProvider override fun onCreate() { super.onCreate() routingRepository.initialize() locationProvider.initialize() } }

Slide 100

Slide 100 text

Scope - Recap class AmazonApplication : Application() { @Inject lateinit var routingRepository: RoutingRepository @Inject lateinit var locationProvider: LocationProvider override fun onCreate() { super.onCreate() routingRepository.initialize() locationProvider.initialize() } }

Slide 101

Slide 101 text

Scope - Recap interface RoutingRepository { fun initialize() suspend fun loadRoute (): Route }

Slide 102

Slide 102 text

Scope - Recap interface RoutingRepository { fun initialize() suspend fun loadRoute (): Route }

Slide 103

Slide 103 text

Scope - Recap class AmazonRoutingRepository @Inject constructor( @IODispatcher dispatcher: CoroutineDispatcher ) : RoutingRepository { private val coroutineScope = CoroutineScope(dispatcher) override fun initialize() { coroutineScope.launch { // Initialize } } override suspend fun loadRoute(): Route = ... }

Slide 104

Slide 104 text

Scope - Recap class AmazonRoutingRepository @Inject constructor( @IODispatcher dispatcher: CoroutineDispatcher ) : RoutingRepository { private val coroutineScope = CoroutineScope(dispatcher) override fun initialize() { coroutineScope.launch { // Initialize } } override suspend fun loadRoute(): Route = ... }

Slide 105

Slide 105 text

Scope - Recap

Slide 106

Slide 106 text

Scope - Recap

Slide 107

Slide 107 text

UI Engine

Slide 108

Slide 108 text

UI Engine Lifecycle managed by us Lifecycle managed by Android Business Logic UI rendering Activity Fragment ViewModel ViewModel flow: Flow operation() flow: Flow operation() Service objects

Slide 109

Slide 109 text

UI Engine ViewModel Activity operation1() operation2() operation3() flow1: Flow flow2: Flow flow3: Flow

Slide 110

Slide 110 text

Previously on droidcon…

Slide 111

Slide 111 text

UI Engine https://www.droidcon.com/2022/09/29/navigation-and-dependency-injection-in-compose/

Slide 112

Slide 112 text

UI Engine - Presenter Activity

Slide 113

Slide 113 text

UI Engine - Presenter Root presenter Activity

Slide 114

Slide 114 text

UI Engine - Presenter Root presenter Onboarding presenter Activity

Slide 115

Slide 115 text

UI Engine - Presenter Root presenter Onboarding presenter Activity Login presenter Registration presenter

Slide 116

Slide 116 text

UI Engine - Presenter Root presenter Onboarding presenter Delivery presenter Activity Login presenter Registration presenter

Slide 117

Slide 117 text

UI Engine - Presenter Root presenter Onboarding presenter Delivery presenter Settings presenter Activity Login presenter Registration presenter

Slide 118

Slide 118 text

UI Engine - Presenter Root presenter Onboarding presenter Delivery presenter Settings presenter Activity Login presenter Registration presenter

Slide 119

Slide 119 text

UI Engine - Presenter Root presenter Onboarding presenter Delivery presenter Settings presenter Activity Login presenter Registration presenter

Slide 120

Slide 120 text

UI Engine Lifecycle managed by us Lifecycle managed by Android Business Logic UI rendering Activity model events Service objects Presenter1 Presenter2 Root presenter

Slide 121

Slide 121 text

UI Engine - Presenter interface MoleculePresenter { @Composable fun present(input: InputT): ModelT } interface BaseModel https://github.com/cashapp/molecule

Slide 122

Slide 122 text

interface Renderer { fun render(model: ModelT) } UI Engine - Presenter

Slide 123

Slide 123 text

UI Engine - Presenter interface Renderer { fun render(model: ModelT) } abstract class ViewRenderer : Renderer { protected abstract fun inflate( activity: Activity, parent: ViewGroup, layoutInflater: LayoutInflater, initialModel: T ): View open fun onDetach() = Unit }

Slide 124

Slide 124 text

UI Engine - Presenter example interface ItineraryListPresenter : MoleculePresenter { data class Model( val itinerary: List, val onEvent: (Event) -> Unit, ) : BaseModel sealed interface Event { class OnSelectStop(val stop: Stop) : Event } }

Slide 125

Slide 125 text

UI Engine - Presenter example interface ItineraryListPresenter : MoleculePresenter { data class Model( val itinerary: List, val onEvent: (Event) -> Unit, ) : BaseModel sealed interface Event { class OnSelectStop(val stop: Stop) : Event } }

Slide 126

Slide 126 text

UI Engine - Presenter example interface ItineraryListPresenter : MoleculePresenter { data class Model( val itinerary: List, val onEvent: (Event) -> Unit, ) : BaseModel sealed interface Event { class OnSelectStop(val stop: Stop) : Event } }

Slide 127

Slide 127 text

UI Engine - Presenter example @ContributesBinding(AppScope::class) class ItineraryListPresenterImpl @Inject constructor( private val itineraryRepository: ItineraryRepository ) : ItineraryListPresenter { @Composable override fun present(input: Unit): Model { val items by itineraryRepository.items.collectAsState() return Model( itinerary = items, onEvent = onEvent { when (it) { is Event.OnSelectStop -> { item -> itineraryRepository.onSelectStop(item.stop) } } } ) } }

Slide 128

Slide 128 text

UI Engine - Presenter example @ContributesBinding(AppScope::class) class ItineraryListPresenterImpl @Inject constructor( private val itineraryRepository: ItineraryRepository ) : ItineraryListPresenter { @Composable override fun present(input: Unit): Model { val items by itineraryRepository.items.collectAsState() return Model( itinerary = items, onEvent = onEvent { when (it) { is Event.OnSelectStop -> { item -> itineraryRepository.onSelectStop(item.stop) } } } ) } }

Slide 129

Slide 129 text

UI Engine - Presenter example @ContributesRenderer class ItineraryListRenderer : ViewBindingRenderer() { override fun inflateViewBinding( activity: Activity, parent: ViewGroup, layoutInflater: LayoutInflater, initialModel: ItineraryListPresenter.Model ): FragmentItineraryListRedesignBinding { val itineraryListLayoutBinding = FragmentItineraryListRedesignBinding.inflate(layoutInflater, parent, false) ... return itineraryListLayoutBinding } override fun renderModel(model: ItineraryListPresenter.Model) { ... } }

Slide 130

Slide 130 text

UI Engine - Presenter example @ContributesRenderer class ItineraryListRenderer : ViewBindingRenderer() { override fun inflateViewBinding( activity: Activity, parent: ViewGroup, layoutInflater: LayoutInflater, initialModel: ItineraryListPresenter.Model ): FragmentItineraryListRedesignBinding { val itineraryListLayoutBinding = FragmentItineraryListRedesignBinding.inflate(layoutInflater, parent, false) ... return itineraryListLayoutBinding } override fun renderModel(model: ItineraryListPresenter.Model) { ... } }

Slide 131

Slide 131 text

UI Engine - Presenter example @ContributesRenderer class ItineraryListRenderer : ViewBindingRenderer() { override fun inflateViewBinding( activity: Activity, parent: ViewGroup, layoutInflater: LayoutInflater, initialModel: ItineraryListPresenter.Model ): FragmentItineraryListRedesignBinding { val itineraryListLayoutBinding = FragmentItineraryListRedesignBinding.inflate(layoutInflater, parent, false) ... return itineraryListLayoutBinding } override fun renderModel(model: ItineraryListPresenter.Model) { ... } }

Slide 132

Slide 132 text

UI Engine - Presenter example @Test fun `test presenter returns a model`() = runTest { val itineraryListPresenter = ItineraryListPresenterImpl(repository) itineraryListPresenter.test { val firstModel = awaitItem() assertThat(firstModel.itinerary).hasSize(3) firstModel.onEvent(ItineraryListPresenter.Event.OnSelectStop(stop1)) val secondModel = awaitItem() assertThat(secondModel.itinerary[1].isSelected()).isTrue() } } https://github.com/cashapp/turbine

Slide 133

Slide 133 text

UI Engine - Presenter example navigation class UserScopePresenter @Inject constructor( private val loggedInPresenter: Provider, private val loggedOutPresenter: Provider, private val userSessionService: UserSessionService, ) : MoleculePresenter { @Composable override fun present(input: Unit): BaseModel { val session by userSessionService.sessionState.collectAsState() return if (session.isLogginIn) { val presenter = remember { loggedInPresenter.get() } presenter.present(userSessionService.scope) } else { val presenter = remember { loggedOutPresenter.get() } presenter.present(Unit) } } }

Slide 134

Slide 134 text

UI Engine - Presenter example navigation class UserScopePresenter @Inject constructor( private val loggedInPresenter: Provider, private val loggedOutPresenter: Provider, private val userSessionService: UserSessionService, ) : MoleculePresenter { @Composable override fun present(input: Unit): BaseModel { val session by userSessionService.sessionState.collectAsState() return if (session.isLogginIn) { val presenter = remember { loggedInPresenter.get() } presenter.present(userSessionService.scope) } else { val presenter = remember { loggedOutPresenter.get() } presenter.present(Unit) } } }

Slide 135

Slide 135 text

UI Engine - Presenter example navigation class UserScopePresenter @Inject constructor( private val loggedInPresenter: Provider, private val loggedOutPresenter: Provider, private val userSessionService: UserSessionService, ) : MoleculePresenter { @Composable override fun present(input: Unit): BaseModel { val session by userSessionService.sessionState.collectAsState() return if (session.isLogginIn) { val presenter = remember { loggedInPresenter.get() } presenter.present(userSessionService.scope) } else { val presenter = remember { loggedOutPresenter.get() } presenter.present(Unit) } } }

Slide 136

Slide 136 text

UI Engine - Presenter example navigation class UserScopePresenter @Inject constructor( private val loggedInPresenter: Provider, private val loggedOutPresenter: Provider, private val userSessionService: UserSessionService, ) : MoleculePresenter { @Composable override fun present(input: Unit): BaseModel { val session by userSessionService.sessionState.collectAsState() return if (session.isLogginIn) { val presenter = remember { loggedInPresenter.get() } presenter.present(userSessionService.scope) } else { val presenter = remember { loggedOutPresenter.get() } presenter.present(Unit) } } }

Slide 137

Slide 137 text

UI Engine - Presenter templates

Slide 138

Slide 138 text

UI Engine - Presenter templates sealed interface Template : BaseModel { data class FullScreenTemplate( val model: BaseModel ) : Template data class ListDetailTemplate( val list: BaseModel, val detail: BaseModel, ) : Template } abstract class TemplateRenderer( ... ) : ViewRenderer()

Slide 139

Slide 139 text

UI Engine - Presenter templates sealed interface Template : BaseModel { data class FullScreenTemplate( val model: BaseModel ) : Template data class ListDetailTemplate( val list: BaseModel, val detail: BaseModel, ) : Template } abstract class TemplateRenderer( ... ) : ViewRenderer()

Slide 140

Slide 140 text

UI Engine - Presenter templates sealed interface Template : BaseModel { data class FullScreenTemplate( val model: BaseModel ) : Template data class ListDetailTemplate( val list: BaseModel, val detail: BaseModel, ) : Template } abstract class TemplateRenderer( ... ) : ViewRenderer()

Slide 141

Slide 141 text

UI Engine - Presenter templates sealed interface Template : BaseModel { data class FullScreenTemplate( val model: BaseModel ) : Template data class ListDetailTemplate( val list: BaseModel, val detail: BaseModel, ) : Template } abstract class TemplateRenderer( ... ) : ViewRenderer()

Slide 142

Slide 142 text

UI Engine - Presenter templates sealed interface Template : BaseModel { data class FullScreenTemplate( val model: BaseModel ) : Template data class ListDetailTemplate( val list: BaseModel, val detail: BaseModel, ) : Template } abstract class TemplateRenderer( ... ) : ViewRenderer()

Slide 143

Slide 143 text

UI Engine - Presenter templates class TemplatePresenter @AssistedInject constructor( private val savedInstanceStateRegistry: SavedInstanceStateRegistry, @Assisted private val rootPresenter: MoleculePresenter, ) : MoleculePresenter { @Composable override fun present(input: Unit): Template { return ReturningCompositionLocalProvider( LocalSavedInstanceStateRegistry provides savedInstanceStateRegistry, ) { rootPresenter.present(Unit).toTemplate() } } @AssistedFactory interface Factory { fun create(rootPresenter: MoleculePresenter): TemplatePresenter } }

Slide 144

Slide 144 text

UI Engine - Presenter templates class TemplatePresenter @AssistedInject constructor( private val savedInstanceStateRegistry: SavedInstanceStateRegistry, @Assisted private val rootPresenter: MoleculePresenter, ) : MoleculePresenter { @Composable override fun present(input: Unit): Template { return ReturningCompositionLocalProvider( LocalSavedInstanceStateRegistry provides savedInstanceStateRegistry, ) { rootPresenter.present(Unit).toTemplate() } } @AssistedFactory interface Factory { fun create(rootPresenter: MoleculePresenter): TemplatePresenter } }

Slide 145

Slide 145 text

UI Engine - Presenter templates class TemplatePresenter @AssistedInject constructor( private val savedInstanceStateRegistry: SavedInstanceStateRegistry, @Assisted private val rootPresenter: MoleculePresenter, ) : MoleculePresenter { @Composable override fun present(input: Unit): Template { return ReturningCompositionLocalProvider( LocalSavedInstanceStateRegistry provides savedInstanceStateRegistry, ) { rootPresenter.present(Unit).toTemplate() } } @AssistedFactory interface Factory { fun create(rootPresenter: MoleculePresenter): TemplatePresenter } }

Slide 146

Slide 146 text

UI Engine - Presenter template Child presenter

Slide 147

Slide 147 text

UI Engine - Presenter template Child presenter Compute new model

Slide 148

Slide 148 text

UI Engine - Presenter template Child presenter Compute new model Template presenter Send model

Slide 149

Slide 149 text

UI Engine - Presenter template Child presenter Compute new model Template presenter Send model Combine models to template

Slide 150

Slide 150 text

UI Engine - Presenter template Child presenter Compute new model Template presenter Send model Combine models to template Activity Send template

Slide 151

Slide 151 text

UI Engine - Presenter template Child presenter Compute new model Template presenter Send model Combine models to template Activity Send template Renderer factory Send model from template

Slide 152

Slide 152 text

UI Engine - Presenter template Child presenter Compute new model Template presenter Send model Combine models to template Activity Send template Renderer factory Send model from template Renderer Send model to right renderer

Slide 153

Slide 153 text

UI Engine - Presenter template Child presenter Compute new model Template presenter Send model Combine models to template Activity Send template Renderer factory Send model from template Renderer Send model to right renderer Render model on screen

Slide 154

Slide 154 text

UI Engine - Presenter template Child presenter Template presenter Activity Renderer factory Renderer Invoke callbacks from models Compute new model Render model on screen Send model Send template Combine models to template Send model from template Send model to right renderer

Slide 155

Slide 155 text

UI Engine - Circuit https://www.youtube.com/watch?v=ZIr_uuN8FEw

Slide 156

Slide 156 text

UI Engine - Recap ViewModel Activity operation1() operation2() operation3() flow1: Flow flow2: Flow flow3: Flow

Slide 157

Slide 157 text

UI Engine - Recap ViewModel Activity operation1() operation2() operation3() flow1: Flow flow2: Flow flow3: Flow

Slide 158

Slide 158 text

UI Engine - Recap Lifecycle managed by us Lifecycle managed by Android Business Logic UI rendering Activity Fragment ViewModel ViewModel flow: Flow operation() flow: Flow operation() Service objects

Slide 159

Slide 159 text

UI Engine - Recap Lifecycle managed by us Lifecycle managed by Android Business Logic UI rendering Activity model events Service objects Presenter1 Presenter2 Root presenter

Slide 160

Slide 160 text

UI Engine - Recap Lifecycle managed by us Lifecycle managed by Android Business Logic UI rendering model events Service objects Presenter1 Presenter2 Root presenter model events Activity1 Activity2

Slide 161

Slide 161 text

Managing State Beyond ViewModels and Hilt Ralf Wondratschek @vRallev | @[email protected] | @ralf_dev