Skip to content

Commit

Permalink
Merge pull request #408 from PatilShreyas/version-2.0.0-dev
Browse files Browse the repository at this point in the history
Release v2.0.0
  • Loading branch information
PatilShreyas committed Feb 20, 2022
2 parents cfb913d + fe8c519 commit c3042cc
Show file tree
Hide file tree
Showing 86 changed files with 3,125 additions and 1,827 deletions.
1 change: 1 addition & 0 deletions docs/_sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- [Setting up project](/pages/noty-android/setting-up-project)
- [Design / Wireframe](pages/noty-android/design-wireframe.md)
- [App Architecture](/pages/noty-android/app-architecture.md)
- [Architecture Revamp v2.0.0](/pages/noty-android/architecture-revamp-v2.0.0.md)
- [End notes](/pages/finish)
- [Changelog](/pages/changelog)
- **Links**
Expand Down
8 changes: 8 additions & 0 deletions docs/pages/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ You can see [GitHub releases](https://github.com/PatilShreyas/NotyKT/releases) w

---

## _v2.0.0_ (2022-02-20)

### 🎯 Codebase Improvements

- [[#397](https://github.com/PatilShreyas/NotyKT/issues/397)] Revamp architecture of NotyKT Android app.

> [**Read more**](/pages/noty-android/architecture-revamp-v2.0.0.md) about the refactoring.
## _v1.3.2_ (2021-11-30)

This release includes a few improvements and fixes in the Jetpack Compose and Simple Application to make them better. All features mentioned below are contributed by [@kasem-sm](https://github.com/kasem-sm)
Expand Down
245 changes: 245 additions & 0 deletions docs/pages/noty-android/architecture-revamp-v2.0.0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
# 🚀 Architecture Revamp (v2.0.0)

## Introduction

Since the beginning of the development of NotyKT application, the Android app followed pure MVVM architecture in which UI layer performs actions via ViewModel and then ViewModel reactively gives response to the UI. Also, this repository is maintaining two different variants of UI development i.e.

1. `simpleapp` for demonstrating usage of traditional UI development with XMLs and binding.
2. `composeapp` for demonstrating usage of modern Android's UI development with Jetpack Compose.

While working on the both variants and maintaining common ViewModels with the current architecture was not looking maintainable in the long run. That's the intention behind this refactoring. Most of the changes happened are about state management around ViewModel and UI layer.

## 🐛 Problems

### ***ViewModel exposing a stream of state for every possible N events***

For example, see this ViewModel

```kotlin
class NoteDetailViewModel(...) : ViewModel() {

private val _note = MutableSharedFlow<Note>()
val note: SharedFlow<Note> = _note.shareWhileObserved(viewModelScope)

private val _updateNoteState = MutableSharedFlow<UIDataState<Unit>>()
val updateNoteState = _updateNoteState.shareWhileObserved(viewModelScope)

private val _deleteNoteState = MutableSharedFlow<UIDataState<Unit>>()
val deleteNoteState = _deleteNoteState.shareWhileObserved(viewModelScope)
}
```

Here, this ViewModel has exposed three streams for possible three different states i.e. note, update note and delete note. For every state, there's a private mutable stream created since it has to be protected from UI layer from the direct mutation.

### ***Composable doesn't fits well with sealed states***

While doing imperative UI development, sealed class-based states helped to properly manage the state in Activities and Fragments. But Jetpack Compose follows declarative UI design paradigms. Also, sealed-class-based state models doesn't play well with the composable and if tried to forcefully use, it ends up making composable component stateful where it can be made stateless.

For example, see this composable which is listening to all the three state streams which are declared in the above ViewModel and there's no initial value provided since it can't be provided. This way, Composable functions doesn't look good since there's no single source of state on which composable should be dependent. *Also, if think of writing UI tests for this function, it would be somehow challenging*

```kotlin
@Composable
fun NoteDetailsScreen(...) {
val note = viewModel.note.collectAsState(initial = null).value
val updateState = viewModel.updateNoteState.collectAsState(initial = null)
val deleteState = viewModel.deleteNoteState.collectAsState(initial = null)
}
```

### ***Some business logic reside on UI side***

Some of the business logic like validating note, title, username, password, etc was executed on UI side instead it should be responsibility of ViewModel to execute it and update the state accordingly.

### ***ViewModel testability***

While using `SharedFlow`s for streaming the state updates, ViewModel's test was not looking well. SharedFlow is hot in nature so while validating the UI states in testing, it's becoming the overhead for collecting states in collection and also need to make sure to collect state changes into the collection from child coroutine and cancelling the job before assertion. See the below example.

```kotlin
Given("A note for updating") {
And("Note is not yet synced") {
val updateStates = mutableListOf<UIDataState<Unit>>()
val collectUpdateStates = launch {
// This is launched in another coroutine because it 🔴
// suspends the call to `toList()` because this is SharedFlow 🔴
viewModel.updateNoteState.toList(updateStates)
}

When("Note is updated") {
viewModel.updateNote(title, note)

Then("Valid UI states should be get emitted") {
// 🔴 If this is not cancelled, test will run infinitely 🔴
collectUpdateStates.cancel()
updateStates[0].isLoading shouldBe true
updateStates[1].isSuccess shouldBe true
}
}
}
}
```

## 🏗️ Refactoring

### Single `State`

Maintaining different state streams for ***N*** use cases was not looking good earlier. Then `State` came into the picture which is **interface** for all the UI states.

```kotlin
/**
* Represents a base type for the state of a UI component
*/
interface State
```

Example of state:

*This is a single state class for the UI of Note details having initial state predefined.* UI will just listen to this class updates and will update state accordingly without having any extra checks.

```kotlin
data class NoteDetailState(
val isLoading: Boolean = false,
val title: String? = null,
val note: String? = null,
val showSave: Boolean = false,
val finished: Boolean = false,
val error: String? = null
) : State
```

### Origin of `BaseViewModel`

Having private mutable stream and pubic immutable stream was overhead. So after thinking from that perspective, `BaseViewModel` came into the picture which was strongly typed with `State`. `StateFlow` is exposed to the UI layer which emits recent state to the UI subscribers.

```kotlin
/**
* Base for all the ViewModels
*/
abstract class BaseViewModel<STATE : State>(initialState: STATE) : ViewModel() {

/**
* Mutable State of this ViewModel
*/
private val _state = MutableStateFlow(initialState)

/**
* State to be exposed to the UI layer
*/
val state: StateFlow<STATE> = _state.asStateFlow()

/**
* Retrieves the current UI state
*/
val currentState: STATE get() = state.value

/**
* Updates the state of this ViewModel and returns the new state
*
* @param update Lambda callback with old state to calculate a new state
* @return The updated state
*/
protected fun setState(update: (old: STATE) -> STATE): STATE =
_state.updateAndGet(update)
}
```

So the implementation looks like the follows. Whenever the need for mutation of state is occurred, the method `setState()` is called and the current state is copied with changing the required fields. This is how state is managed through ViewModel.

```kotlin
class NoteDetailViewModel(...) : BaseViewModel<NoteDetailState>(initialState = NoteDetailState()) {
fun setTitle(title: String) {
setState { state -> state.copy(title = title) }
}

fun setNote(note: String) {
setState { state -> state.copy(note = note) }
}
}
```

### UI state management in Fragments

In the `simpleapp` module, `BaseFragment` then strictly bounded with `State`. Then there's a method `render()` which is invoked whenever state is updated from the ViewModel. Here, the state handling is done.

```kotlin
class NoteDetailFragment : BaseFragment<NoteDetailFragmentBinding, NoteDetailState, NoteDetailViewModel>() {
// ...
override fun render(state: NoteDetailState) {
showProgressDialog(state.isLoading)

binding.fabSave.isVisible = state.showSave

binding.noteLayout.fieldTitle.setText(title)
binding.noteLayout.fieldNote.setText(note)

if (state.finished) {
findNavController().navigateUp()
}

val errorMessage = state.error
if (errorMessage != null) {
toast("Error: $errorMessage")
}
}
}
```

### UI state management in Composables

After the refactoring, composables improved a lot. The state management became better than earlier in `composeapp` module. Like in the example follows, `NoteDetailScreen` listens to the ViewModel state changes and thus becomes stateful and it provided all the necessary states to the `NoteDetailContent()` composable and also listen to the events and passes events as an action to the ViewModel. Thus, `NoteDetailContent()` completely becomes a Stateless composable.

```kotlin
@Composable
fun NoteDetailsScreen(navController: NavHostController, viewModel: NoteDetailViewModel) {
val state by viewModel.collectState()

NoteDetailContent(
title = state.title ?: "",
note = state.note ?: "",
error = state.error,
showSaveButton = state.showSave,
onTitleChange = viewModel::setTitle,
onNoteChange = viewModel::setNote,
onSaveClick = viewModel::save,
onDeleteClick = { showDeleteNoteConfirmation = true },
onNavigateUp = { navController.navigateUp() }
)
}
```

### All business logic in ViewModel, only UI and rendering process on UI side

After the refactoring, all the core business logic of the application moved to the ViewModel. ViewModels executes the business, updates the state and accordingly UI processes the state and renders the components.

### Testing of states and ViewModel became easy

The testing of ViewModel and validating the UI states became very easy after the refactoring which was not good with the previous implementation. See the example:

```kotlin
Given("Note contents") {
And("Note contents are invalid") {
val title = "hi"
val note = ""

When("When note contents are set") {
viewModel.setTitle(title)
viewModel.setNote(note)

Then("UI state should have validation details") {
viewModel.withState {
this.title shouldBe title
this.note shouldBe note
showSave shouldBe false
}
}
}
}
}
```

## 🤔 Conclusion

This refactoring of the NotyKT application improved the quality of codebase and taught lessons to improvise the architecture of the application. These learnings will be beneficial for the readers for choosing the right architecture for their application and that's the main aim of writing this document.

---

> ***Refer to [this Pull request](https://github.com/PatilShreyas/NotyKT/pull/398) to see the changes made to revamp the architecture.***
6 changes: 5 additions & 1 deletion docs/pages/noty-android/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ It connects with the Noty REST API to save and retrieve data.
- [x] Clean and Simple Material UI 🎨
- [x] Dark mode 🌗
- [x] Jetpack Compose UI
- [ ] Tests ***(WIP)***
- [x] Tests

## 📙 Overview of Codebase

Expand Down Expand Up @@ -89,3 +89,7 @@ For single source of data. Implements `local` and `remote` modules.
- [Accompanist](https://google.github.io/accompanist/) - Accompanist is a group of libraries that aim to supplement Jetpack Compose with features that are commonly required by developers but not yet available.

- [LeakCanary](https://square.github.io/leakcanary/) - Memory leak detection library for Android

- [Kotest](https://kotest.io/) - Kotest is a flexible and elegant multi-platform test framework for Kotlin with extensive assertions and integrated property testing

- [Mockk](https://mockk.io/) - Mocking library for Kotlin
2 changes: 2 additions & 0 deletions noty-android/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ Design of this awesome application is implemented by [Sanju S](https://github.co
- [Jetpack Compose UI Toolkit](https://developer.android.com/jetpack/compose) - Modern UI development toolkit.
- [Accompanist](https://google.github.io/accompanist/) - Accompanist is a group of libraries that aim to supplement Jetpack Compose with features that are commonly required by developers but not yet available.
- [LeakCanary](https://square.github.io/leakcanary/) - Memory leak detection library for Android
- [Kotest](https://kotest.io/) - Kotest is a flexible and elegant multi-platform test framework for Kotlin with extensive assertions and integrated property testing
- [Mockk](https://mockk.io/) - Mocking library for Kotlin

## Modules

Expand Down
1 change: 1 addition & 0 deletions noty-android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ dependencies {
// Lifecycle
api "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion"
api "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion"
api "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycleVersion"

// WorkManager
implementation "androidx.work:work-runtime-ktx:$workmanagerVersion"
Expand Down
6 changes: 5 additions & 1 deletion noty-android/app/composeapp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ dependencies {
implementation "androidx.compose.material:material:$composeVersion"
implementation "androidx.compose.material:material-icons-core:$composeVersion"
implementation "androidx.compose.material:material-icons-extended:$composeVersion"
implementation "androidx.compose.ui:ui-tooling:$composeVersion"
debugImplementation "androidx.compose.ui:ui-tooling:$composeVersion"
implementation "androidx.compose.ui:ui-tooling-preview:$composeVersion"
implementation "androidx.compose.ui:ui-test:$composeVersion"

// Dagger + Hilt
Expand Down Expand Up @@ -157,6 +158,9 @@ dependencies {
// Hilt Compose Navigation
implementation "androidx.hilt:hilt-navigation-compose:$hiltComposeNavVersion"

// Capturable
implementation "dev.shreyaspatil:capturable:$capturableVersion"

// Testing
testImplementation "junit:junit:$jUnitVersion"

Expand Down

This file was deleted.

0 comments on commit c3042cc

Please sign in to comment.