This library is inspired by React SWR ported for Jetpack Compose and Compose Multiplatform.
Supported platforms are Android, Desktop, iOS and Web.
The API specification of React SWR is followed as much as possible.
Options are also supported for the most part.
According to React SWR, "SWR" refers to
The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
- Android
- Android 6.0 (API level 23) or later
- iOS/Desktop/Web
Add the following gradle dependency exchanging *.*.* for the latest release.
implementation("com.kazakago.swr:swr-compose:*.*.*")As with React SWR, implement the "fetcher function" and set it with the key to rememberSWR().
Using Kotlin's Destructuring declarations for return values can be written in the same way as in React SWR.
private val fetcher: suspend (key: String) -> String = {
getNameApi.execute(key)
}
@Composable
fun Profile() {
val (data, error) = rememberSWR("/api/user", fetcher)
if (error != null) {
Text("failed to load")
} else if (data == null) {
Text("loading...")
} else {
Text("hello $data!")
}
}Live demo of Kotlin/Wasm is here.
Refer to the example module for details. This module works as an Compose Multiplatform app.
| Feature name | Note |
|---|---|
| Global Configuration | |
| Data Fetching | |
| Error Handling | |
| Auto Revalidation | |
| Conditional Data Fetching | |
| Arguments | |
| Mutation | |
| Pagination | |
| Prefetching Data | Available by useSWRPreload() |
The following options are supported for React SWR.
https://swr.vercel.app/docs/options
| Option name | Default value |
|---|---|
| revalidateIfStale | true |
| revalidateOnMount | true |
| revalidateOnFocus | true |
| revalidateOnReconnect | true |
| refreshInterval | 0.seconds (disable) |
| refreshWhenHidden | false |
| refreshWhenOffline | false |
| shouldRetryOnError | true |
| dedupingInterval | 2.seconds |
| focusThrottleInterval | 5.seconds |
| loadingTimeout | 3.seconds |
| errorRetryInterval | 5.seconds |
| errorRetryCount | |
| fallback | |
| keepPreviousData | false |
| onLoadingSlow(key, config) | |
| onSuccess(data, key, config) | |
| onError(err, key, config) | |
| onErrorRetry(err, key, config, revalidate, revalidateOps) | Exponential backoff algorithm |
Deduplication and Deep Comparison are supported, but Dependency Collection is not supported due to Kotlin's language specification.
Therefore, the number of re-rendering (re-compose) may be higher than in the original React SWR.
However, it is possible to prevent performance degradation by limiting the number of arguments passed to child Composable functions (e.g., only data).