簡體   English   中英

Android | Kotlin | 流 - 不能轉換為 kotlinx.coroutines.flow.StateFlow

[英]Android | Kotlin | Flow - cannot be cast to kotlinx.coroutines.flow.StateFlow

我試圖讓自己熟悉DataStore ,所以在我當前的項目中,我正在嘗試使用它。

在我的依賴中。 我已經添加:

    implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06"

然后我創建了這個 class 來處理數據存儲:

class BasicDataStore(context: Context) :
    PrefsDataStore(
        context,
        PREF_FILE_BASIC
    ),
    BasicImpl {
    override val serviceRunning: Flow<Boolean>
        get() = dataStore.data.map { preferences ->
            preferences[SERVICE_RUNNING_KEY] ?: false
        }
    override suspend fun setServiceRunningToStore(serviceRunning: Boolean) {
        dataStore.edit { preferences ->
            preferences[SERVICE_RUNNING_KEY] = serviceRunning
        }
    }
    companion object {
        private const val PREF_FILE_BASIC = "basic_preference"
        private val SERVICE_RUNNING_KEY = booleanPreferencesKey("service_running")
    }
}
@Singleton
interface BasicImpl {
    val serviceRunning: Flow<Boolean>
    suspend fun setServiceRunningToStore(serviceRunning: Boolean)
}

在我的視圖模型中,我正在嘗試使用該值,如下所示:

class MainViewModel(application: Application) : AndroidViewModel(application) {
    ...
    private val basicDataStore = BasicDataStore(application)
    val serviceRunning
            : StateFlow<Boolean> get()
            = basicDataStore.serviceRunning as StateFlow<Boolean>
    fun setServiceRunning(serviceRunning: Boolean) {
        viewModelScope.launch(IO) {
            basicDataStore.setServiceRunningToStore(serviceRunning)
        }
    }
}

但它給了我以下錯誤:

Caused by: java.lang.ClassCastException: com.mua.roti.data.datastore.BasicDataStore$serviceRunning$$inlined$map$1 cannot be cast to kotlinx.coroutines.flow.StateFlow
        at com.mua.roti.viewmodel.MainViewModel.getServiceRunning(MainViewModel.kt:33)
...

在 xml 中,在 UI 部分:


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{main.serviceRunning.value.toString()}" />

使用 viewmodel,一切都變得如此酷炫和簡單,易於閱讀和實現。 現在我對Flow感到困惑。 謝謝。

流的層次結構如下: StateFlow -> SharedFlow -> Flow

所以你不能真正轉換它,如果你想將冷流轉換為熱 StateFlow,你應該使用stateIn()運算符。 在你的情況下:

val serviceRunning: StateFlow<Boolean> 
    get() = basicDataStore.serviceRunning.stateIn(viewModelScope, SharingStarted.Lazily, false)

您可能會調整狀態流的SharingStarted和/或初始值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM