-
Notifications
You must be signed in to change notification settings - Fork 449
Architecture Overview
The app architecture has three layers: a data layer, a domain layer and a UI layer.
The architecture follows a reactive programming model with unidirectional data flow. With the data layer at the bottom, the key concepts are:
- Higher layers react to changes in lower layers.
- Events flow down.
- Data flows up.
The data flow is achieved using streams, implemented using Kotlin Flows.
The data layer is where all the UI-independent data is stored and retrieved. It consists of raw data sources and higher-level "repository" and "manager" classes.
Note that any functions exposed by a data layer class that must perform asynchronous work do so by exposing suspending functions that may run inside coroutines while any streaming sources of data are handled by exposing Flows.
Each repository has its own models. For example, the BeneficiaryRepository
has a Beneficiary
model and the InvoiceRepository
has a Invoice
model.
Repositories are the public API for other layers, they provide the only way to access the app data. The repositories typically offer one or more methods for reading and writing data.
In some cases a source of data may be continuously observed and in these cases a repository may choose to expose a StateFlow that emits data updates using the DataState wrapper.
The lowest level of the data layer are the "data source" classes. These are the raw sources of data that include data persisted in to Datastore, data retrieved from network requests using Ktorfit, and data retrieved via interactions with the Mifos Fineract Backend.
Note: that these data sources are constructed in a manner that adheres to a very important principle of the app: that function calls should not throw exceptions (see the style and best practices documentation for more details.) In the case of data sources, this tends to mean that suspending functions like those representing network requests should return a Result type. This is an important responsibility of the data layer as a wrapper around other third party libraries, as dependencies like ktorfit and Ktor tend to throw exceptions to indicate errors instead.
Repository classes represent the outermost level of the data layer. They can take data sources, managers, and in rare cases even other repositories as dependencies and are meant to be exposed directly to the UI layer. They synthesize data from multiple sources and combine various asynchronous requests as necessary in order to expose data to the UI layer in a more appropriate form. These classes tend to have broad responsibilities that generally cover a major domain of the app, such as authentication (AuthenticationRepository) or self service (SelfServiceRepository).
Repository classes also feature functions that do not throw exceptions, but unlike the lower levels of the data layer the Result type should be avoided in favor of custom sealed classes that represent the various success/error cases in a more processed form. Returning raw Throwable/Exception instances as part of "error" states should be avoided when possible.
In some cases a source of data may be continuously observed and in these cases a repository may choose to expose a StateFlow that emits data updates using the DataState wrapper.
The domain layer contains use cases. These are classes which have a single invocable method (operator fun invoke
) containing business logic.
These use cases are used to simplify and remove duplicate logic from ViewModels. They typically combine and transform data from repositories.
For example, LoginUseCase
combines and update data from the AuthenticationRepository
and ClientRepository
to log in a user.
Notably, the domain layer in this project does not (for now) contain any use cases for event handling. Events are handled by the UI layer calling methods on repositories directly.
The UI layer adheres to the concept of unidirectional data flow and makes use of the MVVM design pattern. Both concepts are in line what Google currently recommends as the best approach for building the UI-layer of a modern Android application and this allows us to make use of all the available tooling Google provides as part of the Jetpack suite of libraries. The MVVM implementation is built around the Android ViewModel class and the UI itself is constructed using the Jetpack Compose, a declarative UI framework specifically built around the unidirectional data flow approach.
Each screen in the app is associated with at least the following three classes/files:
- A
...ViewModel
class responsible for managing the data and state for the screen. - A
...Screen
class that contains the Compose implementation of the UI. - A
...Navigation
file containing the details for how to add the screen to the overall navigation graph and how navigate to it within the graph.
The app's approach to MVVM is based around the handling of "state", "actions", and "events" and is encoded in the BaseViewModel class.
-
State: The "state" represents the complete internal and external total state of the ViewModel (VM). Any and all information needed to configure the UI that is associated with the VM should be included in this state and is exposed via the
BaseViewModel.stateFlow
property asStateFlow<S>
(whereS
represents the unique type of state associated with the VM). This state is typically a combination of state from the data layer (such as account information) and state from the UI layer (such as data entered into a text field).There should be no additional
StateFlow
exposed from a VM that would represent some other kind of state; all state should be represented byS
. Additionally, any internal state not directly needed by the UI but which influences the behavior of the VM should be included as well in order to keep all state managed by the VM in a single place. -
Actions: The "actions" represent interactions with the VM in some way that could potentially cause an update to that total state. These can be external actions coming from the user's interaction with the UI, like click events, or internal actions coming from some asynchronous process internal to the VM itself, like the result of some suspending functions. Actions are sent by interacting directly with
BaseViewModel.actionChannel
or by using theBaseViewModel.sendAction
andBaseViewModel.trySendAction
helpers. All actions are then processed synchronously in a queue in thehandleAction
function.It is worth emphasizing that state should never be updated inside a coroutine in a VM; all asynchronous work that results in a state update should do so by posting an internal action. This ensures that the only place that state changes can occur is synchronously inside the
handleAction
function. This makes the process of finding and reasoning about state changes easier and simplifies debugging. -
Events: The "events" represent discrete, one-shot side-effects and are typically associated with navigation events triggered by some user action. They are sent internally using
BaseViewModel.sendEvent
and may be consumed by the UI layer via theBaseViewModel.eventFlow
property. An EventsEffect should typically be used to simplify the consumption of these events.
VMs are typically injected using Koin.
This allows them to be constructed, retrieved, and cached in the Compose UI layer by calling koinViewModel()
with the appropriate type.
Dependencies passed into the VM constructor will typically be singletons of the graph, such as SelfServiceRepository.
In cases where the VM needs to initialized with some specific data (like an ID) that is sent from the previous screen,
this data should be retrieved by injecting the SavedStateHandle
and pulling out data using a type-safe wrapper (ex: BeneficiaryAddEditArgs).
The following is an example that demonstrates many of the above principles and best practices when using BaseViewModel
to implement a VM. It has the following features:
- It is injected with a repository (
ExampleRepository
) that provides streamingExampleData
and aSavedStateHandle
in order to pull initial data using aExampleArgs
wrapper class. - It has state that manages several properties of interest to the UI:
exampleData
,isToggledEnabled
, anddialogState
. - It receives external actions from the UI (
ContinueButtonClick
andToggleValueUpdate
) as well as internal actions launch from inside different coroutines coroutines (Internal.ExampleDataReceive
,Internal.ToggleValueSync
). These actions result in state updates or the emission of an event (NavigateToNextScreen
). - It saves the current state to the
SavedStateHandle
in order to restore it later after process death and restoration. This ensures the user's actions and associated state will not be lost if the app goes into the background and is temporarily killed by the OS to conserve memory.
Show example
private const val KEY_STATE = "state"
@HiltViewModel
class ExampleViewModel @Inject constructor(
private val exampleRepository: ExampleRepository,
private val savedStateHandle: SavedStateHandle,
) : BaseViewModel<ExampleState, ExampleEvent, ExampleAction>(
// If previously saved state data is present in the SavedStateHandle, use that as the initial
// state, otherwise initialize from repository and navigation data.
initialState = savedStateHandle[KEY_STATE] ?: ExampleState(
exampleData = exampleRepository.exampleDataStateFlow.value,
isToggleEnabled = ExampleArgs(savedStateHandle).isToggleEnabledInitialValue,
dialogState = null,
)
) {
init {
// As the state updates, write to saved state handle for retrieval after process death and
// restoration.
stateFlow
.onEach { savedStateHandle[KEY_STATE] = it }
.launchIn(viewModelScope)
exampleRepository
.exampleDataStateFlow
// Asynchronously received data is converted to an internal action and sent in order to
// be handled by `handleAction`.
.map { ExampleAction.Internal.ExampleDataReceive(it) }
.onEach(::sendAction)
.launchIn(viewModelScope)
}
override fun handleAction(action: ExampleAction) {
when (action) {
is ExampleAction.ContinueButtonClick -> handleContinueButtonClick()
is ExampleAction.ToggleValueUpdate -> handleToggleValueUpdate(action)
is ExampleAction.Internal -> handleInternalAction(action)
}
}
private fun handleContinueButtonClick() {
// Update the state to show a dialog
mutableStateFlow.update {
it.copy(
dialogState = ExampleState.DialogState.Loading,
)
}
// Run a suspending call in a coroutine to fetch data and post the result back as an
// internal action for further processing so that all state changes and event emissions
// happen synchronously in `handleAction`.
viewModelScope.launch {
val completionData = exampleRepository
.fetchCompletionData(isToggleEnabled = state.isToggleEnabled)
sendAction(
ExampleAction.Internal.CompletionDataReceive(
completionData = completionData,
)
)
}
}
private fun handleToggleValueUpdate(action: ExampleAction.ToggleValueUpdate) {
// Update the state
mutableStateFlow.update {
it.copy(
isToggleEnabled = action.isToggleEnabled,
)
}
}
private fun handleInternalAction(action: ExampleAction.Internal) {
when (action) {
is ExampleAction.Internal.CompletionDataReceive -> handleCompletionDataReceive(action)
is ExampleAction.Internal.ExampleDataReceive -> handleExampleDataReceive(action)
}
}
private fun handleCompletionDataReceive(action: ExampleAction.Internal.CompletionDataReceive) {
// Update the state to clear the dialog
mutableStateFlow.update {
it.copy(
dialogState = null,
)
}
// Send event with data from the action to navigate
sendEvent(
ExampleEvent.NavigateToNextScreen(
completionData = action.completionData,
)
)
}
private fun handleExampleDataReceive(action: ExampleAction.Internal.ExampleDataReceive) {
// Update the state
mutableStateFlow.update {
it.copy(
exampleData = action.exampleData,
)
}
}
}
@Parcelize
data class ExampleState(
val exampleData: String,
val isToggleEnabled: Boolean,
val dialogState: DialogState?,
) : Parcelable {
sealed class DialogState : Parcelable {
@Parcelize
data object Loading : DialogState()
}
}
sealed class ExampleEvent {
data class NavigateToNextScreen(
val completionData: CompletionData,
) : ExampleEvent()
}
sealed class ExampleAction {
data object ContinueButtonClick : ExampleAction()
data class ToggleValueUpdate(
val isToggleEnabled: Boolean,
) : ExampleAction()
sealed class Internal : ExampleAction() {
data class CompletionDataReceive(
val completionData: CompletionData,
) : Internal()
data class ExampleDataReceive(
val exampleData: String,
) : Internal()
}
}
Each unique screen destination is represented by a composable ...Screen
function annotated with @Composable
. The responsibilities of this layer include:
- Receiving "state" data from the associated
ViewModel
and rendering the UI accordingly. - Receiving "events" from the associated
ViewModel
and taking the corresponding action, which is typically to trigger a passed-in callback function for navigation purposes. An EventsEffect should be used to simplify this process. - Sending "actions" to the
ViewModel
indicating user interactions or UI-layer events as necessary. - Interacting with purely UI-layer "manager" classes that are not appropriate or possible to be injected into the
ViewModel
(such as those concerning permissions or camera access).
In order to both provide consistency to the app and to simplify the development of new screens,
an extensive system of reusable composable components has been developed and may be found in the components package.
These tend to bear the prefix Mifos...
to easily distinguish them from similar OS-level components. If there is any new unique UI component that is added, it should always be considered if it should be made a shareable component.
Jetpack Compose is built around the idea that the state required to render any given composable function can be "hoisted" to higher levels that may need access to that state. This means that the responsibility for keeping track of the current state of a component may not typically reside with the component itself. It is important, therefore, to understand where the best place is to manage any given piece of UI state.
This is discussed in detail in Google's state-hoisting documentation and can be summarized roughly as follows: state should be hoisted as high as is necessary to perform any relevant logic and no higher. This is a pattern that is followed in the Mobile Wallet app and tends to lead to the following:
-
Any state that will eventually need to be used by the VM should be hoisted to the VM. For example, any text input, toggle values, etc. that may be updated by user interactions should be completely controlled by the VM. These state changes are communicated via the "actions" that the Compose layer sends, which trigger corresponding updates the VM's total "state".
-
Any UI state that will not be used by logic inside the VM should remain in the UI layer. For example, visibility toggle states for password inputs should typically remain out of the VM.
These rules can lead to some notable differences in how certain dialogs are handled. For example, loading dialogs are controlled by events that occur in the VM, such as when a network request is started and when it completes. This requires the VM to be in charge of managing the visibility state of the dialog. However, some dialogs appear as the result of clicking on an item in the UI in order to simply display information or to ask for the user's confirmation before some action is taken. Because there is no logic in the VM that depends on the visibility of these particular dialogs, their visibility state can be controlled by the UI. Note, however, that any user interaction that results in a navigation to a new screen should always be routed to the VM first, as the VM should always be in charge of triggering changes at the per-screen level.
The following shows off the basic structure of a composable ...Screen
implementation. Note that:
-
The VM is "injected" using the
koinViewModel()
helper function. This will correctly create, cache, and scope the VM in production code while making it easier to pass in mock/fake implementations in test code. -
An
onNavigateToNextScreen
function is also passed in, which can be called to trigger a navigation via a call to a NavController in the outer layers of the navigation graph. Passing in a function rather than theNavController
itself decouples the screen code from the navigation framework and greatly simplifies the testing of screens. -
The VM "state" is consumed using
viewModel.stateFlow.collectAsStateWithLifecycle()
. This will cause the composable to "recompose" and update whenever updates are pushed to theviewModel.stateFlow
. -
The VM "events" are consumed using an EventsEffect and demonstrate how the
onNavigateToNextScreen
may be triggered. -
The current state of the text, switch, and button are hoisted to the VM and pulled out from the
state
. User interactions with the switch and button result in "actions" being sent to the VM usingviewModel.trySendAction
. -
Reusable components (
MifosLoadingDialog
,MifosScaffold
, andMifosButton
) are used where possible in order to build the screen using the correct theming and reduce code duplication. When this is not possible (such as when rending theText
composable) all colors and styles are pulled from the MifosTheme object.
Show example
@Composable
fun ExampleScreen(
onNavigateToNextScreen: (CompletionData) -> Unit,
viewModel: ExampleViewModel = hiltViewModel(),
) {
// Collect state
val state by viewModel.stateFlow.collectAsStateWithLifecycle()
// Handle events
EventsEffect(viewModel = viewModel) { event ->
when (event) {
is ExampleEvent.NavigateToNextScreen -> {
onNavigateToNextScreen(event.completionData)
}
}
}
// Show state-based dialogs if necessary
when (state.dialogState) {
ExampleState.DialogState.Loading -> {
MifosLoadingDialog(
visibilityState = LoadingDialogState.Shown(
text = R.string.loading.asText(),
)
)
}
else -> Unit
}
// Render the remaining state
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.verticalScroll(rememberScrollState()),
) {
Text(
text = state.exampleData,
textAlign = TextAlign.Center,
style = MifosTheme.typography.headlineSmall,
color = MifosTheme.colorScheme.textColors.primary,
modifier = Modifier
.padding(horizontal = 24.dp)
.wrapContentHeight(),
)
Spacer(modifier = Modifier.height(16.dp))
MifosFilledButton(
label = stringResource(id = R.string.continue_text),
onClick = remember(viewModel) {
{ viewModel.trySendAction(ExampleAction.ContinueButtonClick) }
},
modifier = Modifier
.padding(horizontal = 16.dp)
.fillMaxWidth(),
)
}
}
- Join Firebase Android App Testing - https://appdistribution.firebase.dev/i/87a469306176a52a
- Kotlin Multiplatform - https://www.jetbrains.com/help/kotlin-multiplatform-dev/get-started.html
- JetBrains Toolbox - https://www.jetbrains.com/toolbox-app/
- Compose Multiplatform - https://www.jetbrains.com/compose-multiplatform/
- Fastlane - https://docs.fastlane.tools/