Offline Support
Mobile devices are not always guaranteed a network connection.
The solution to that problem comes in the form of OfflinePlugin
, a layer of persistence which provides the following benefits:
- Decreases initial load times, especially when the network connection is poor.
- Enables the user to see cached channels and messages while offline.
- Enables the user to perform actions such as sending messages and reactions while offline.
Configuration
In most cases we strongly recommend using offline support as it significantly improves the user experience, however, certain types of applications (for example focused on livestreaming) don't require it.
In order to keep the core SDK size smaller, the OfflinePlugin
is published as a separate library and needs to be configured as described below:
Firstly, you need to add an offline
dependency:
dependencies {
implementation "io.getstream:stream-chat-android-offline:$stream_version"
}
The next step is to connect the OfflinePlugin
to the ChatClient
:
- Kotlin
- Java
val offlinePluginFactory = StreamOfflinePluginFactory(appContext = context)
ChatClient.Builder(apiKey, context)
.withPlugins(offlinePluginFactory)
.build()
StreamOfflinePluginFactory offlinePluginFactory = new StreamOfflinePluginFactory(context);
new ChatClient.Builder("apiKey", context).withPlugins(offlinePluginFactory).build();
That's it. From now on, users' channels, messages and reactions will be saved into offline storage, so they can interact with the chat without an Internet connection.
Accessing Offline Storage
The OfflinePlugin
acts as a persistence layer - its responsible for saving data into the offline storage, so that it can be accessed later even if the application was killed.
If you want to access stored data or sync actions performed offline, the easiest way is to add the StatePlugin
which exposes a bunch of state related objects.
You can learn more about the StatePlugin
here.
Supported Operations
Besides storing lists of channels, messages or reactions, the offline library allows you to perform the following actions without an Internet connection:
- Creating a channel
- Sending, updating and deleting a message
- Sending and deleting reactions
The StatePlugin
is responsible for syncing actions performed offline. You should consider using both plugins together.
Clearing Offline Storage
The offline storage is persisted even when the application has been killed.
You can clear it during user disconnection by passing the flushPersistence = true
flag:
- Kotlin
- Java
chatClient.disconnect(flushPersistence = true).enqueue { result ->
when(result) {
is Result.Success -> {
// Handle success
}
is Result.Failure -> {
// Handle error
}
}
}
boolean flushPersistence = true;
chatClient.disconnect(flushPersistence).enqueue((result) -> {
if (result.isSuccess()) {
// Handle success
} else {
// Handle error
}
});
This will wipe all of the user's data from the storage.