Google在Android Jetpack组件中引入了DataStore库,它可以轻松地在Android应用程序中存储Key-Value类型的数据。在某些情况下,我们需要使用不同的配置文件来存储不同类型的数据。下面是如何使用DataStore来创建多个配置文件的示例代码:
val dataStore1 = context.createDataStore(name = "dataStore1")
val dataStore2 = context.createDataStore(name = "dataStore2")
syntax = "proto2";
package com.myapp.data;
message UserSettings {
int32 userId = 1;
bool darkTheme = 2;
}
message AppSettings {
bool sound = 1;
bool notifications = 2;
}
syntax = "proto2";
package com.myapp.data;
message UserSettingsProfile1 {
int32 userId = 1;
bool darkTheme = 2;
}
message UserSettingsProfile2 {
string userName = 1;
int32 themeColor = 2;
}
message AppSettingsProfile1 {
bool sound = 1;
bool notifications = 2;
}
message AppSettingsProfile2 {
bool adsEnabled = 1;
bool analyticsEnabled = 2;
}
val userSettingsDataStoreProfile1 = dataStore1.data
.catch { exception ->
if (exception is IOException) {
emit(UserSettingsProfile1.getDefaultInstance())
} else {
throw exception
}
}.map { userSettingsData ->
// Convert from protos
UserSettings(userId = userSettingsData.userId, darkTheme = userSettingsData.darkTheme)
}
val appSettingsDataStoreProfile1 = dataStore1.data
.catch { exception ->
if (exception is IOException) {
emit(AppSettingsProfile1.getDefaultInstance())
} else {
throw exception
}
}.map { appSettingsData ->
// Convert