提问人:PEDY 提问时间:9/11/2023 最后编辑:PEDY 更新时间:9/11/2023 访问量:36
LiveData 从 PreferencesDataStore 的 Flow 获取时始终为 null - android
LiveData is null always when get from Flow of preferencesDataStore - android
问:
我正在使用如下风箱:preferencesDataStore
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = PREFERENCES_NAME)
class DataStoreOperationsImpl(context: Context) : DataStoreOperations {
private object PreferencesKey {val custom_font = stringPreferencesKey(name = TYPE_FONT)}
private val dataStore = context.dataStore
override fun getFonts(): Flow<CustomTypeFont> {
return dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
CustomTypeFont(
preferences[PreferencesKey.custom_font] ?: TYPE_FONT
)
} .onStart { emit(CustomTypeFont(TYPE_FONT)) }
}
}
和:
interface DataStoreOperations {fun getFonts(): Flow<CustomTypeFont>}
和:
class DataStoreRepository @Inject constructor(
private val dataStore: DataStoreOperations
) {
fun getFontInvoked(): Flow<CustomTypeFont> {
return dataStore.getFonts()
}
}
和:
class GetCustomTypeFontsUseCase(
private val dataStoreRepository: DataStoreRepository
) {
operator fun invoke(): Flow<CustomTypeFont> {
return dataStoreRepository.getFontInvoked()
}
}
和:
data class DataStoreUseCases @Inject constructor(
val getCustomTypeFonts: GetCustomTypeFontsUseCase
)
和:
@HiltViewModel
class AccountViewModel @Inject constructor(
private val app: Application,
private val dataStoreUseCases: DataStoreUseCases
) : ViewModel() {
val customFont: LiveData<CustomTypeFont> = dataStoreUseCases.getCustomTypeFonts().asLiveData().map { it }
}
在我的xml中,我使用:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="FT"
type="com.my.amvulibrary.presentation.ui.fragments.account.viewmodel.AccountViewModel" />
</data>
<TextView
android:id="@+id/txtTitleAccount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginRight="20dp"
android:ellipsize="marquee"
android:singleLine="true"
android:text="@string/settings"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold"
app:fonta="@{FT.customFont}" />
</androidx.constraintlayout.widget.ConstraintLayout>
在我的片段中是:
companion object {
@JvmStatic
@BindingAdapter("app:fonta")
fun setFont(textView: TextView, fontName: LiveData<CustomTypeFont>?) {
fontName?.value?.let { font ->
val typeface = Typeface.createFromAsset(
textView.context.assets,
"fonts/${font.tpFont}"
)
textView.typeface = typeface
}
}
}
但 in 始终为 null。我能做些什么?fontName
setFont
答: 暂无答案
评论