java.lang.IllegalStateException:同一文件有多个活动数据存储:/data/user/0/com.firstgoalkeeper.firstgoalkeeper/files/datastore/player_pref.preferences_pb。您应该将 DataStore 保持为单例,或者确认同一文件上没有两个 DataStore 处于活动状态(通过确认范围已取消)。
class Constants {
companion object{
const val PLAYER_PREFERENCE = "player_pref"
val PLAYER_SELECTION_KEY = intPreferencesKey("player_selection")
}
}
abstract class PrefsDataStore(context: Context, fileName: String) {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
fileName
)
val mdataStore: DataStore<Preferences> = context.dataStore
}
class PlayerSelectionDataStore(context: Context) : PrefsDataStore(context,
PLAYER_PREFERENCE) {
suspend fun storeIndex(index: Int) {
mdataStore.edit {
it[PLAYER_SELECTION_KEY] = index
}
}
val userSelectionFlow: Flow<Int> = mdataStore.data.map {
it[PLAYER_SELECTION_KEY] ?: 4
}
}
@Composable
fun PlayerSelection() {
val context = LocalContext.current
val playerSelectionDataStore = PlayerSelectionDataStore(context)
var index by remember {
mutableStateOf(4)
}
Log.d("index", "PlayerSelection: we are at index ${index} ")
Log.d("index", "PlayerSelection: we select ${allTeamsLists[index].name} ")
Row(
verticalAlignment = Alignment.CenterVertically, modifier = Modifier
.fillMaxSize()
.background(color = goalkeeperBackground)
) {
// ...
Box(
modifier = Modifier
.clickable {
GlobalScope.launch {
playerSelectionDataStore.storeIndex(index)
}
Toast
.makeText(
context,
"${allTeamsLists[index].name} player is Selected ",
Toast.LENGTH_SHORT
)
.show()
}
...
) {...}
我做错了什么并建议最佳做法。