В моем фоновом работнике , у меня есть асинхронный метод, который загружает данные в серверную часть после того, как пользователь нажимает кнопку «Сохранить».
Код: Выделить всё
override suspend fun doWorkWithRetry(): Result = coroutineScope {
val one = processCreatedReceipts()
if (one.await() * other async methods *) {
Result.success()
} else {
throw RuntimeException("Failed to upload data")
}
}
@OptIn(DelicateCoroutinesApi::class)
private fun processCreatedReceipts() = GlobalScope.async {
val data: List = expensesRepo.findAllBySyncState(SyncState.UNSYNCED)
data.parallelStream().forEach { expense ->
val dto = expense.asCreateDto()
expensesService.createReceipt(dto).run { r, t ->
t?.let {
expensesRepo.updateSyncStateById(expense.id, SyncState.SYNC_FAILED)
throw RuntimeException("Data sync failed with error: ${t.message}")
}
r?.data?.result?.let { result ->
* save to received data to db *
}
}
}
}
Код: Выделить всё
@Query(
"""
SELECT *
FROM files
WHERE resourceId == :id and sync_state is not 'PENDING_DELETE'
"""
)
abstract fun findByIdFlow(id: String?): Flow
Код: Выделить всё
val list: Flow = repo.findByIdFlow(userId)
Код: Выделить всё
lifecycleScope.launch(Dispatchers.IO) {
viewModel.list.collect {
lifecycleScope.launch(Dispatchers.Main) {
* update UI *
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... r-and-flow
Мобильная версия