Я новичок в Android Wear и работаю над обновлением данных об осложнениях каждые 10 секунд в проекте «Пример осложнений Android».
Я использую класс DataStorage для обновления данных, а ShortTextDataSourceService будет наблюдать за данные изменяются и обновляются. Но данные об осложнениях обновляются так быстро, что предполагается, что они будут обновляться каждые 10 секунд. Вот мой код, что я сделал не так?
Класс ShortTextDataSourceService:
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
private val dataStorage = DataStorage(this)
override fun onCreate() {
super.onCreate()
observeComplicationData(this)
dataStorage.startScheduledUpdates()
}
private fun observeComplicationData(context: Context) {
scope.launch {
dataStorage.observeComplicationState().collect { newState ->
Log.d("ShortTextDataSourceService", "Data updated: $newState")
val componentName = ComponentName(
context,
ShortTextDataSourceService::class.java
)
val requester = ComplicationDataSourceUpdateRequester.create(
context,
componentName
)
requester.requestUpdateAll()
Log.d("ShortTextDataSourceService", "Complication update requested---.")
}
}
}
override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? {
Log.d("ShortTextDataSourceService", "OLD VALUE :::> $updateCount")
updateCount = dataStorage.observeComplicationState().first().toString()
Log.d("ShortTextDataSourceService", "NEW VALUE :::> $updateCount")
}
Класс DataStorage:
private val COMPLICATION_STATE_KEY = longPreferencesKey("complication_state")
class DataStorage(private val context: Context) {
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
fun startScheduledUpdates() {
Log.d("ShortTextDataSourceService", "Scheduled Updates--only once")
scope.launch {
while (true) {
updateComplicationState()
delay(30000) // 10 seconds
}
}
}
suspend fun updateComplicationState() {
var newValue = 0L
context.dataStore.edit { preferences ->
val currentValue = preferences[COMPLICATION_STATE_KEY] ?: 0L
newValue = currentValue + 1
preferences[COMPLICATION_STATE_KEY] = newValue
}
}
fun observeComplicationState(): Flow {
Log.d("DataStorage", "Observe Updates--")
return context.dataStore.data.map { preferences ->
preferences[COMPLICATION_STATE_KEY] ?: 0L
}
}
}
val Context.dataStore: DataStore by preferencesDataStore(
name = "Complications",)
Подробнее здесь: https://stackoverflow.com/questions/793 ... frequently