Simple Implementation of Android Proto DataStore
Previously, we’ve talked about Preferences DataStore. In this article, we will talk about the second type of DataStore, Proto DataStore or DataStore Typed.
Let’s make a simple application that demonstrates the usage of Proto DataStore.
Where’s the source code?
tl;dr
Proto DataStore uses protocol buffers (protobuf) for providing type safety. Protobuf enables you to define all kinds of types for your DataStore, including maps, enumeration, and nested types.
If you run the source code of this article, you would see Proto DataStore in action:
As you can see, this simple application can persist values between app’s sessions.
Step by Step Explanation
Follow the steps provided below to make the application shown above.
1. Open Android Studio. Create new project with “Empty Activity” option.
2. Add datastore
, protobuf-javalite
and lifecycle-runtime-ktx
dependencies in your app/build.gradle
file. We need protobuf-javalite
library to generate DataStore classes defined in Protobuf schemas. We also need Lifecycle library because we need to use Coroutine to be able to use Flow.
We also need to add com.google.protobuf
plugin and Protobuf’s configuration block here. Take a look at code snippet below.
3. Next up, is building the layout, activity_main.xml
. Here’s what it looks like and the code needed below:
main_activity.xml
will look like.4. Next, we are going to define the Protobuf schema for our DataStore. Create a new file called user_prefs.proto
in the app/src/main/proto
folder. Copy paste the code snippet below to the file. Notice that here, we declare 3 variables with different types for our Proto DataStore class: example_int
, example_string
, and example_bool
.
After creating this file, make sure to build your project. If build succeeded, a class named UserPreferences
will be generated for you.
5. Next, we will create a Serializer object. Serializer object specifies how to read and write to your Proto DataStore class. Create a new Kotlin file named MyDataStoreTypedSerializer.kt
and copy paste the code below.
5. Lastly, we are going to update the MainActivity.kt
. You can copy paste the code below directly, but here’s the summary of how it works. First, we obtain the DataStore object using dataStore
. Then for each primitive data types (Int
, String
, and Boolean
), we retrieve previous stored DataStore value and also set a listener for updating the DataStore value.
6. That’s it! Now run the app on your device and try it for yourself. Try updating the values several times and then closing the app. When you reopen the app, the values should be persisted.
As always, thanks for reading!