Skip to content

Instantly share code, notes, and snippets.

@G00fY2
Last active December 12, 2024 19:17
Show Gist options
  • Save G00fY2/21781d271c57442a413313d4f6992bc1 to your computer and use it in GitHub Desktop.
Save G00fY2/21781d271c57442a413313d4f6992bc1 to your computer and use it in GitHub Desktop.
@Module
@InstallIn(SingletonComponent::class)
internal object DataStoreModule {
@Provides
@Singleton
fun provideMyCacheDataStore(
@ApplicationContext context: Context,
moshi: Moshi,
): DataStore<MyCachedDataClass> {
return DataStoreFactory.create(
produceFile = { context.dataStoreFile("MY_CACHE_DATA_SOURCE.json") },
serializer = DataStoreJsonSerializer(
defaultValue = MyCachedDataClass(),
provideJsonAdapter = { moshi.adapter(MyCachedDataClass::class.java) },
),
corruptionHandler = ReplaceFileCorruptionHandler { MyCachedDataClass() },
)
}
}
class DataStoreJsonSerializer<T>(
override val defaultValue: T,
// use function to provide moshi adapter to prevent initiating on main thread
private val provideJsonAdapter: () -> JsonAdapter<T>,
) : Serializer<T> {
override suspend fun readFrom(input: InputStream): T {
return try {
input.source().buffer().use {
checkNotNull(provideJsonAdapter().fromJson(it))
}
} catch (e: Exception) {
logInfo(e) { "Unable to read datastore" }
throw CorruptionException("Unable to read datastore", e) // handled by corruptionHandler
}
}
override suspend fun writeTo(t: T, output: OutputStream) {
try {
output.sink().buffer().use {
provideJsonAdapter().toJson(it, t)
}
} catch (e: Exception) {
logError(e) { "Unable to write to datastore" }
}
}
}
@nizarnaufal-kpvdev
Copy link

can u provide if handle list in object ?, i think the code is a problem with moshi list adapter

@G00fY2
Copy link
Author

G00fY2 commented Dec 3, 2024

There are no special usages or restrictions in regards to Moshi. You can see from the code that we just call fromJson and toJson. Please check out the Moshi documentation to see how to use specific type adapters like for lists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment