Skip to content

Commit 8faa856

Browse files
Babelia13yamidragutadriangl
authored
Migrate lib to coroutines and remove RX dependencies
This PR aims to update the master branch of the repo with the changes made in the masmovil forked repo. It contains major changes related to a library migration to Kotlin coroutines instead of RX. Copyright information in all necessary classes has also updated. Co-authored-by: yamidragut <[email protected]> Co-authored-by: Adrián García <[email protected]>
1 parent fba1ad2 commit 8faa856

File tree

99 files changed

+2609
-1700
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

99 files changed

+2609
-1700
lines changed

Diff for: .github/CODEOWNERS

+7-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
# Each line is a file pattern followed by one or more owners.
33

44
# Current code owners
5-
# @adriangl -> Adrián García
5+
# - @nicolasmertanen -> Nicolás Mertanen
6+
# - @finxo -> Alejandro Lopez
7+
# - @FrangSierra -> Francisco García
8+
# - @adriangl -> Adrián García
9+
# - @yamidragut -> Estefanía Sarasola
10+
# - @Babelia13 -> Sara Lucía Pérez
611

7-
* @adriangl
12+
* @nicolasmertanen @finxo @FrangSierra @adriangl @yamidragut @Babelia13

Diff for: .github/dependabot.yml

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
version: 2
2+
updates:
3+
# Updates for Gradle dependencies used in the app
4+
- package-ecosystem: gradle
5+
directory: "/"
6+
schedule:
7+
interval: "monthly"
8+
open-pull-requests-limit: 10

Diff for: .gitignore

-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,6 @@ hs_err_pid*
151151
# Icon must end with two \r
152152
Icon
153153

154-
155154
# Thumbnails
156155
._*
157156

Diff for: CHANGELOG.md

+9-2
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1818
### Security
1919
- No security issues fixed!
2020

21+
## [3.0.0] - 2021-06-10
22+
### Changed
23+
- BREAKING CHANGE: Remove RX packages, moved API to full coroutines.
24+
### Changed
25+
- Add support for injecting view models scoped to the navigation component's graph in Jetpack Compose.
26+
2127
## [2.0.0] - 2021-05-01
2228
### Changed
2329
- Changed repo ownership to [hyperdevs-team](https://github.com/hyperdevs-team). Thanks [bq](https://github.com/bq) for all the work!
@@ -33,7 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3339

3440
## [1.3.2] - 2020-05-27
3541
### Added
36-
- Add `allTerminal`, `onAllTerminal` and `firstExceptionOrNull` functions to lists of `Resource`s
42+
- Add `allTerminal`, `onAllTerminal` and `firstExceptionOrNull` functions to lists of `Resource`s.
3743

3844
## [1.3.1] - 2020-04-22
3945
### Added
@@ -114,7 +120,8 @@ state (`success` or `failure`)
114120
### Added
115121
- Initial architecture release.
116122

117-
[Unreleased]: https://github.com/hyperdevs-team/mini-kotlin/compare/2.0.0...HEAD
123+
[Unreleased]: https://github.com/hyperdevs-team/mini-kotlin/compare/3.0.0...HEAD
124+
[3.0.0]: https://github.com/hyperdevs-team/mini-kotlin/compare/2.0.0...3.0.0
118125
[2.0.0]: https://github.com/hyperdevs-team/mini-kotlin/compare/1.4.0...2.0.0
119126
[1.4.0]: https://github.com/hyperdevs-team/mini-kotlin/compare/1.3.3...1.4.0
120127
[1.3.3]: https://github.com/hyperdevs-team/mini-kotlin/compare/1.3.2...1.3.3

Diff for: README.md

+81-37
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# Mini
22
[![Release](https://jitpack.io/v/hyperdevs-team/mini-kotlin.svg)](https://jitpack.io/#hyperdevs-team/mini-kotlin)
33

4+
## ⚠️ DOCS HAVE TO BE UPDATED FOR VERSION 3.x.y
5+
46
Mini is a minimal Flux architecture written in Kotlin that also adds a mix of useful features to build UIs fast.
57

68
## Purpose
@@ -9,24 +11,24 @@ Feature development using Mini is fast compared to traditional architectures (li
911

1012
## How to Use
1113
### Dispatcher
12-
The *Dispatcher* is the hub that manages all data flow in a Flux application. It is basically a holder of store callbacks: each store registers itself and provides a callback for an action.
14+
The *Dispatcher* is the hub that manages all data flow in a Flux application. It is basically a holder of store callbacks: each store registers itself and provides a callback for an action.
1315

1416
One important thing is that the dispatching is always performed in the same thread to avoid possible side-effects.
1517

1618
We can dispatch actions in the following ways:
1719

1820
```kotlin
1921
// Dispatch an action on the main thread synchronously
20-
dispatcher.dispatch(LoginAction(username = "user", password = "123"))
22+
dispatcher.dispatch(action = LoginAction(username = "user", password = "123"))
2123

22-
// Post an event that will dispatch the action on the UI thread and return immediately.
23-
dispatcher.dispatchAsync(LoginAction(username = "user", password = "123"))
24+
// Dispatch an action on the given scope
25+
dispatcher.dispatchOn(action = LoginAction(username = "user", password = "123"), scope = coroutineScope)
2426
```
2527

2628
### Store
27-
The *Stores* are holders for application state and state mutation logic. In order to do so they expose pure reducer functions that are later invoked by the dispatcher.
29+
The *Stores* are holders for application state and state mutation logic. In order to do so they expose pure reducer functions that are later invoked by the dispatcher. A *Store* is a type of a *StateContainer*, which is exactly that: a container of states.
2830

29-
The state is a plain object (usually a `data class`) that holds all information needed to display the view. States should always be inmutable. State classes should avoid using framework elements (View, Camera, Cursor...) in order to facilitate testing.
31+
The state is a plain object (usually a `data class`) that holds all information needed to display the view. States should always be immutable. State classes should avoid using framework elements (View, Camera, Cursor...) in order to facilitate testing.
3032

3133
Stores subscribe to actions to change the application state after a dispatch. Mini generates the code that links dispatcher actions and stores using the `@Reducer` annotation over a **non-private function that receives an Action as parameter**.
3234

@@ -52,43 +54,38 @@ An *Action* is a simple class that usually represents a use case. It can also co
5254

5355
For example, we may want to log in to a service. We would create an action like this one:
5456
```kotlin
57+
@Action
5558
data class LoginAction(val username: String, val password: String)
5659
```
5760

5861
When we receive the response from the server, we'll dispatch another action with the result:
5962
```kotlin
63+
@Action
6064
data class LoginCompleteAction(val loginTask: Task, val user: User?)
6165
```
6266

6367
Actions will usually be triggered from Views or Controllers.
6468

6569
### View changes
66-
Each ``Store`` exposes a custom `StoreCallback` though the method `observe` or a `Flowable` if you want to make use of RxJava. Both of them emits changes produced on their states, allowing the view to listen reactive the state changes. Being able to update the UI according to the new `Store` state.
70+
Each ``StateContainer`` exposes a Kotlin `Flow` that emits changes produced on the state, allowing the view to listen reactive those changes. Being able to update the UI according to the new `StateContainer` state.
6771

68-
```kotlin
69-
//Using RxJava
70-
userStore
71-
.flowable()
72-
.map { it.name }
73-
.subscribe { updateUserName(it) }
74-
75-
// Custom callback
76-
userStore
77-
.observe { state -> updateUserName(state.name) }
72+
```kotlin
73+
mainStore.flow()
74+
.onEach { state ->
75+
// Do whatever you want
76+
}.launchInLifecycleScope()
7877
```
7978

80-
If you make use of the RxJava methods, you can make use of the `SubscriptionTracker` interface to keep track of the `Disposables` used on your activities and fragments.
81-
8279
### Tasks
83-
A `Task` is a basic object to represent an ongoing process. They should be used in the state of our `Store` to represent ongoing processes that must be represented in the UI.
80+
A `Task` is a basic object to represent an ongoing process. They should be used in the state of our `StateContainer` (a `Store`, for example) to represent ongoing processes that must be represented in the UI.
8481

8582
You can also use `TypedTask` to save metadata related the current task.
8683

8784
**IMPORTANT: Do not use TypedTask to hold values that must survive multiple task executions. Save them as a variable in the state instead.**
8885

8986

9087
### Example
91-
Given the example Stores and Actions explained before, the workflow will be:
88+
Given the example Stores and Actions explained before, the workflow would be:
9289

9390
- View dispatches `LoginAction`.
9491
- Store changes his `LoginTask` status to running and call though his SessionController which will do all the async work to log in the given user.
@@ -97,12 +94,18 @@ Given the example Stores and Actions explained before, the workflow will be:
9794
- The Store changes his state to the given values from `LoginCompleteAction`.
9895
- The View redirect to the HomeActivity if the task was success or shows an error if not.
9996

100-
## Rx Utils
101-
Mini includes some utility extensions over RxJava 2.0 to make easier listen state changes over the `Stores`.
97+
You can execute another sample in the `app` package. It contains two different samples executing two types of `StateContainer`s:
98+
- `StoreSampleActivity` class uses a `Store` as a `StateContainer`.
99+
- `ViewModelSampleActivity` class uses a `ViewModel` as a `StateContainer`.
102100

103-
- `mapNotNull`: Will emit only not null values over the given `map` clause.
104-
- `select`: Like `mapNotNull` but avoiding repeated values.
105-
- `onNextTerminalState`: Used to map a `Task` inside an state and listen the next terminal state(Success - Error). Executing a different closure depending of the result of the task.
101+
## Kotlin Flow Utils
102+
Mini includes some utility extensions over Kotlin `Flow` to make easier listen state changes over the `StateContainer`s.
103+
104+
- `select`: Will emit only not null values over the given `map` clause.
105+
- `selectNotNull`: Like `select` but avoiding null values.
106+
- `onEachChange`: Emits a value when the values goes from one value to another.
107+
- `onEachDisable`: Emits when the value goes from true to false.
108+
- `onEachEnable`: Emits when the value goes from false to true.
106109

107110
## Navigation
108111
To avoid loops over when working with navigation based on a process result. You will need to make use of `onNextTerminalState` after dispatch and `Action` that starts a process which result could navigate to a different screen.
@@ -120,11 +123,11 @@ For example:
120123
If we continually listen the changes of a `Task` and we navigate to a specific screen when the `Task` becomes successful. The state will stay on SUCCESS and if we navigate back to the last screen we will be redirected again.
121124

122125
## Logging
123-
Mini includes a custom `LoggerInterceptor` to log any change in your `Store` states produced from an `Action`. This will allow you to keep track of your actions, changes and side-effects more easily.
124-
To add the LoggerInterceptor to your application you just need to add a single instance of it to your `Dispatcher` after initialize it in your `Application` class or dependency injection code.
126+
Mini includes a custom `LoggerMiddleware` to log any change in your `StateContainer` states produced from an `Action`. This will allow you to keep track of your actions, changes and side-effects more easily.
127+
To add the LoggerMiddleware to your application you just need to add a single instance of it to your `Dispatcher` after initialize it in your `Application` class or dependency injection code.
125128
```kotlin
126-
val loggerInterceptor = CustomLoggerInterceptor(stores().values)
127-
dispatcher.addInterceptor(loggerInterceptor)
129+
val loggerMiddleware = CustomLoggerMiddleware(stores().values)
130+
dispatcher.addMiddleware(loggerMiddleware)
128131
```
129132

130133
## Testing with Mini
@@ -184,18 +187,16 @@ Add the following dependencies to your app's `build.gradle`:
184187

185188
```groovy
186189
dependencies {
187-
def mini_version = "2.0.0"
190+
def mini_version = "3.0.0"
188191
// Minimum working dependencies
189192
implementation "com.github.hyperdevs-team.mini-kotlin:mini-android:$mini_version"
190193
kapt "com.github.hyperdevs-team.mini-kotlin:mini-processor:$mini_version"
191194
192-
// RxJava 2 helper libraries
193-
implementation "com.github.hyperdevs-team.mini-kotlin:mini-rx2:$mini_version"
194-
implementation "com.github.hyperdevs-team.mini-kotlin:mini-rx2-android:$mini_version"
195-
196195
// Kodein helper libraries
197196
implementation "com.github.hyperdevs-team.mini-kotlin:mini-kodein:$mini_version"
198197
implementation "com.github.hyperdevs-team.mini-kotlin:mini-kodein-android:$mini_version"
198+
// Kodein helper library for view models scoped to the Navigation component's graph in Jetpack Compose
199+
implementation "com.github.hyperdevs-team.mini-kotlin:mini-kodein-android-compose:$mini_version"
199200
200201
// Testing helper libraries
201202
androidTestImplementation "com.github.hyperdevs-team.mini-kotlin:mini-testing:$mini_version"
@@ -241,12 +242,55 @@ stores.forEach { store ->
241242
store.initialize()
242243
}
243244

244-
// Optional: add logging interceptor to log action events
245-
dispatcher.addInterceptor(LoggerInterceptor(stores)) { tag, msg ->
245+
// Optional: add logging middleware to log action events
246+
dispatcher.addMiddleware(LoggerMiddleware(stores)) { tag, msg ->
246247
Log.d(tag, msg)
247248
}
248249
```
249250

251+
### \[Android] Kodein Android utils
252+
`mini-kodein-android` has some utility methods in order to inject an Android's `ViewModel` in a `DIAware` `Activity` or `Fragment`.
253+
In order to use them, bind the Android's `ViewModelProvider.Factory` instance with Kodein:
254+
```kotlin
255+
// Use any tag to differ between the injected `Context` or `Application` if you are binding also `Context` with Kodein
256+
bind<Application>("appTag") with singleton { app }
257+
bind<ViewModelProvider.Factory>() with singleton { DIViewModelFactory(di.direct) }
258+
```
259+
To inject a ViewModel without parameters, bind it as follows:
260+
```kotlin
261+
bindViewModel { MainViewModel(instance("appTag") }
262+
```
263+
And in your `DIAware` `Activity` or `Fragment`:
264+
```kotlin
265+
private val mainViewModel: MainViewModel by viewModel()
266+
```
267+
268+
`mini-kodein-android-compose` has some utility methods in order to inject an Android's `ViewModel` in the scope of a Navigation component
269+
graph. This is useful as in Jetpack Compose it is common to have only one or few `Activities` and no `Fragment`s so, in order to scope
270+
the lifecycle of the `ViewModel` not for all the life of the `Activity`, we can scope it to any route existing in the `NavBackStackEntry`.
271+
In order to use it, do the same as above, but instead of injecting the ViewModel scoped to a route of the Navigation, the `NavHost` composable
272+
must be inside an `DIAware Activity`, and then do as follows:
273+
```kotlin
274+
composable(route = "home") { navBackStackEntry ->
275+
val homeViewModel: HomeViewModel by navBackStackEntry.viewModel(contextDI())
276+
HomeScreen(homeViewModel, ...)
277+
}
278+
```
279+
280+
In case you want to pass an argument to a ViewModel, you need to bind the factory of that kind of Android's ViewModel.
281+
You can do this in both `mini-kodein-android`, and `mini-kodein-android-compose`.
282+
For example, given a `ViewModel` that you want to pass a `String` param, it would be:
283+
```kotlin
284+
bindViewModelFactory<HomeViewModelWithParameter, ViewModelProvider.Factory> { param ->
285+
TypedViewModelFactory(HomeViewModelWithParameter::class, instance("appTag"), param as String)
286+
}
287+
```
288+
And to retrieve it with the given param in its constructor:
289+
```kotlin
290+
val param = "Hello World!"
291+
val homeViewModelWithParameter: HomeViewModelWithParameter by navBackStackEntry.viewModel(contextDI(), param)
292+
```
293+
250294
### \[Android] Proguard/R8
251295
Each of the libraries contain a sensible proguard file that your project can consume in order to run you app on Proguard or R8.
252296
No additional steps have to be done in order to use them apart from enabling minify in your project.

0 commit comments

Comments
 (0)