Skip to content

KazaKago/swr-compose

Repository files navigation

SWR for Compose Android

Maven Central javadoc Test License

This is a clone library of React SWR ported for Jetpack Compose.
Currently works only on Android.

The API specification of React SWR is followed as much as possible.
Options are also supported for the most part.

What's "SWR"?

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.

Requirements

Min SDK 23+

Install

Add the following gradle dependency exchanging *.*.* for the latest release. Maven Central

implementation("com.kazakago.swr.compose:swr-android:*.*.*")

Getting Started

As with React SWR, implement the "fetcher function" and set it with the key to useSWR().
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) = useSWR("/api/user", fetcher)

    if (error != null) {
        Text("failed to load")
    } else if (data == null) {
        Text("loading...")
    } else {
        Text("hello $data!")
    }
}

Example

Refer to the example module for details. This module works as an Android app.

Supported Features

Feature name Status Note
Options See below
Global Configuration
Data Fetching
Error Handling
Auto Revalidation
Conditional Data Fetching
Arguments
Mutation ✅️
Pagination
Prefetching Data ✅️ Available by useSWRPreload()
Suspense
Middleware

Supported Options

The following options are supported for React SWR.
https://swr.vercel.app/docs/options

Option name Status Default value
suspense
fetcher(args)
revalidateIfStale true
revalidateOnMount true if fallbackData is not set
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
fallbackData
keepPreviousData false
onLoadingSlow(key, config)
onSuccess(data, key, config)
onError(err, key, config)
onErrorRetry(err, key, config, revalidate, revalidateOps) Exponential backoff algorithm
compare(a, b)
isPaused() false
use

Notice for performance

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).