Last active
December 12, 2024 19:17
-
-
Save G00fY2/21781d271c57442a413313d4f6992bc1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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" } | |
} | |
} | |
} |
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
can u provide if handle list in object ?, i think the code is a problem with moshi list adapter