我正在尝试使用Kotlin序列化和Hilt来实现Proto Datastore。
参考:https://medium.com/androiddevelopers/using-datastore-with-kotlin-serialization-6552502c5345
我无法使用新的DataStore创建语法注入DataStore对象。
@InstallIn(SingletonComponent::class)
@Module
object DataStoreModule {
@ExperimentalSerializationApi
@Singleton
@Provides
fun provideDataStore(@ApplicationContext context: Context): DataStore<UserPreferences> {
val Context.dataStore: DataStore<UserPreferences> by dataStore(
fileName = "user_pref.pb",
serializer = UserPreferencesSerializer
)
return dataStore
}
}我收到了lint消息Local extension properties are not allowed
如何注入这个Kotlin扩展属性?或者有没有办法注入dataStore对象?
发布于 2021-09-10 18:57:40
您不能在本地上下文中使用扩展,您应该这样调用:
@InstallIn(SingletonComponent::class)
@Module
object DataStoreModule {
@ExperimentalSerializationApi
@Singleton
@Provides
fun provideDataStore(@ApplicationContext context: Context): DataStore<UserPreferences> =
DataStoreFactory.create(
serializer = UserPreferencesSerializer,
produceFile = { context.dataStoreFile("user_pref.pb") },
)
}发布于 2021-06-28 01:11:00
我找到了一种使用Predefined qualifers in Hilt实现这一点的方法
现在没有DataStoreModule类了。我直接将应用程序上下文注入到Datastore Manager类中。下面是代码。
@Singleton
class DataStoreManager @Inject constructor(
@ApplicationContext private val context: Context,
) {
private val Context.userPreferencesDataStore: DataStore<UserPreferences> by dataStore(
fileName = "user_pref.pb",
serializer = UserPreferencesSerializer
)
val userPreferencesFlow: Flow<UserPreferences> =
context.userPreferencesDataStore.data.catch { exception ->
// dataStore.data throws an IOException when an error is encountered when reading data
if (exception is IOException) {
Timber.e("Error reading sort order preferences. $exception")
emit(UserPreferences())
} else {
throw exception
}
}
suspend fun updateUid(uid: String) {
context.userPreferencesDataStore.updateData { userPreferences ->
userPreferences.copy(uid = uid)
}
}
suspend fun getUid(): String {
return userPreferencesFlow.first().uid
}
}这就像一个护身符。
https://stackoverflow.com/questions/68139174
复制相似问题