-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
README.md
291 lines (234 loc) · 9.29 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="asset/flower-logo_white.png">
<img width="300" height="300" src="asset/flower-logo_black.png">
</picture>
</p>
Flower is a Kotlin multi-platform (originally, Android) library that makes networking and database caching easy. It enables developers to
fetch network resources and use them as is OR combine them with local database at single place with
fault-tolerant architecture.
![release](https://img.shields.io/github/v/release/hadiyarajesh/flower)
![contributors](https://img.shields.io/github/contributors/hadiyarajesh/flower)
## Special thanks
A special thanks to [JetBrains](https://www.jetbrains.com/community/opensource) for sponsoring the [tools](https://www.jetbrains.com/lp/intellij-frameworks) required to develop this project.
<p >
<picture>
<source media="(prefers-color-scheme: dark)" srcset="asset/flower-logo_white.png">
<img width="100" height="100" src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png">
</picture>
</p>
## Why Flower?
- It helps you to handle different states (`Loading`, `Success`, `EmptySuccess`, `Error`) of
resources efficiently.
- It helps you to use local data in case of network unavailability.
- It provides a fluid app experience by not blocking the `main thread` when accessing
network/database resources.
Flower is recognised by [Google Dev Library](https://devlibrary.withgoogle.com/products/android/repos/hadiyarajesh-flower), a showcase of open-source projects.
## Installation
Flower is primarily available in two modules, one for **Ktorfit** and the other for **Retrofit**.
If you want to handle networking yourself, you can also use the **core** module.
`$flowerVersion=3.1.0`
<br>
`$ktorFitVersion=1.0.0-beta16`
<br>
`$retrofitVersion=2.9.0`
### Ktorfit
This is a multiplatform module. It is suitable for use in Kotlin multiplatform projects, Android (Apps/Libraries), the JVM in general, Kotlin-JS, and so on...
It uses and provides [Ktorfit](https://github.com/Foso/Ktorfit) and you must use KSP in your project.
Apply the KSP Plugin to your project:
```gradle
plugins {
id("com.google.devtools.ksp") version "1.7.10-1.0.6"
}
```
**Multiplatform example**
```gradle
dependencies {
implementation("io.github.hadiyarajesh.flower-ktorfit:flower-ktorfit:$flowerVersion")
add("kspCommonMainMetadata", "de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorFitVersion")
add("kspJvm", "de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorFitVersion")
add("kspAndroid", "de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorFitVersion")
add("kspIosX64", "de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorFitVersion")
add("kspJs", "de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorFitVersion")
add("kspIosSimulatorArm64", "de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorFitVersion")
}
```
**Android example**
```gradle
dependencies {
implementation("io.github.hadiyarajesh.flower-ktorfit:flower-ktorfit:$flowerVersion")
//Ktorfit library
implementation("de.jensklingenberg.ktorfit:ktorfit-lib:$ktorFitVersion")
ksp("de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorFitVersion")
}
```
### Retrofit
This is an Android-only module, so it can only be used in Android Apps/Libs.
```gradle
dependencies {
implementation("io.github.hadiyarajesh.flower-retrofit:flower-retrofit:$flowerVersion")
// Retrofit library
implementation("com.squareup.retrofit2:retrofit:$retrofitVersion")
}
```
### Core
This module only contains the _core code_ and allows you to handle the networking yourself.
**We Highly recommend you to use either Ktorfit or Retrofit module. Only use this if you don't want
to rely on Ktorfit or Retrofit.**
```gradle
dependencies {
implementation("io.github.hadiyarajesh:flower-core:$flowerVersion")
}
```
## Usage
Assume you have a model class called `MyModel` that you are retrieving from the network.
```kotlin
data class MyModel(
val id: Long,
val data: String
)
```
### Prerequisite
- If you want to save network response in a local database, your database caching system function must return a value of type `Flow<MyModel>`.
**Android Room example:**
```kotlin
@Dao
interface MyDao {
@Query("SELECT * FROM Data")
fun getLocalData(): Flow<MyModel>
}
```
- Return type of networking api function must be `ApiResponse<MyModel>` (
or `Flow<ApiResponse<MyModel>>` if you're retrieving a flow of data from server)
**Ktorfit/Retrofit example:**
```kotlin
interface MyApi {
@GET("data")
suspend fun getRemoteData(): ApiResponse<MyModel>
// OR
@GET("data")
fun getRemoteData(): Flow<ApiResponse<MyModel>>
}
```
<br></br>
#### 1. Add CallAdapterFactory/ResponseConverter in networking client
**Ktorfit**
Add `FlowerResponseConverter` as *ResponseConverter* in Ktorfit builder.
```kotlin
Ktorfit.Builder()
.baseUrl(BASE_URL)
.httpClient(ktorClient)
.responseConverter(FlowerResponseConverter())
.build()
```
**Retrofit**
Add `FlowerCallAdapterFactory` as *CallAdapterFactory* in Retrofit builder
```kotlin
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(FlowerCallAdapterFactory.create())
.build()
```
<br></br>
#### 2. Make network request (and save data) in Repository
**2.1** If you want to fetch network resources and save into local database,
use `dbBoundResource()` higher order function
(or `dbBoundResourceFlow()` function if you're retrieving a flow of data from server).
It takes following functions as parameters.
- *fetchFromLocal* - A function to retrieve data from local database
- *shouldMakeNetworkRequest* - Decides whether or not to make network request
- *makeNetworkRequest* - A function to make network request
- *processNetworkResponse* - A function to process network response (e.g., saving response headers before saving actual data)
- *saveResponseData* - A function to save network response (`MyModel`) to local database
- *onNetworkRequestFailed* - An action to perform when a network request fails
```kotlin
fun getMyData(): Flow<Resource<MyModel>> {
return dbBoundResources(
fetchFromLocal = { myDao.getLocalData() },
shouldMakeNetworkRequest = { localData -> localData == null },
makeNetworkRequest = { myApi.getRemoteData() },
processNetworkResponse = { },
saveResponseData = { myDao.saveMyData(it) },
onNetworkRequestFailed { errorMessage, statusCode -> }
).flowOn(Dispatchers.IO)
}
```
**OR**
**2.2** If you only want to fetch network resources without saving it in local database,
use `networkResource()` higher order function.
(or `networkResourceFlow()` function if you're retrieving a flow of data from server)
```kotlin
fun getMyData(): Flow<Resource<MyModel>> {
return networkResource(
makeNetworkRequest = { myApi.getRemoteData() },
onNetworkRequestFailed { errorMessage, statusCode -> }
).flowOn(Dispatchers.IO)
}
```
<br></br>
#### 3. Collect `Flow` to observe different state of resources (`Loading`, `Success`, `Error`) In ViewModel
```kotlin
// A model class to re-present UI state
sealed class UiState<out T> {
object Empty : UiState<Nothing>()
data class Loading(val data: T?) : UiState<out T>()
data class Success<out T>(val data: T & Any) : UiState<T & Any>()
data class Error(val msg: String?) : UiState<Nothing>()
}
```
```kotlin
private val _myData: MutableStateFlow<UiState<MyModel>> = MutableStateFlow(UiState.Empty)
val myData: StateFlow<UiState<MyModel>> = _myData.asStateFlow()
init {
viewModelScope.launch {
getMyData()
}
}
suspend fun getMyData() = repository.getMyData().collect { response ->
when (response.status) {
is Resource.Status.Loading -> {
val status = response.status as Resource.Status.Loading
_myData.value = UiState.Loading(status.data)
}
is Resource.Status.Success -> {
val status = response.status as Resource.Status.Success
_myData.value = UiState.Success(status.data)
}
// EmptySuccess is for potentially body-less successful HTTP responses like 201, 204
is Resource.Status.EmptySuccess -> {
_myData.value = UiState.Empty
}
is Resource.Status.Error -> {
val status = response.status as Resource.Status.Error
_myData.value = UiState.Error(status.message)
}
}
}
```
<br></br>
#### 4. Observe data in Activity/Fragment/Composable function to drive UI changes
```kotlin
lifecycleScope.launchWhenStarted {
viewModel.myData.collect { data ->
when (data) {
is UiState.Loading -> {
// Show loading
}
is UiState.Success -> {
// Show success
}
is UiState.Error -> {
// Show error
}
else -> {}
}
}
}
```
## Sample
Two sample apps are provided in this repository
1. [XML View based app](https://github.com/hadiyarajesh/flower/tree/master/app) - It fetch random quote from remote api and save it to local database in order to display it on UI.
2. [Jetpack Compose based app](https://github.com/hadiyarajesh/flower/tree/master/compose-app) - It fetches unsplash images from [Picsum](https://picsum.photos) and display it on UI.
## License
[Apache License 2.0](https://github.com/hadiyarajesh/flower/blob/master/LICENSE)