i am using Hilt and Coroutine Worker to request API and after fetching data i wanna upsert it to my room repositry , the problem here is even i used withContext(Dispatchers.IO) it trow this error:
Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
by the way i don't wanna enable allowMainThreadQueries() on my room and still wanna update my repo in IO Thread
and my worker code:
@HiltWorker
class CheckForNewProfilePhotos @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val usersAPI: UsersAPI,
private val rUserRepository: RUserRepository
) :
CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
withContext(Dispatchers.IO) {
val usersIdsToFetch = inputData.getLongArray("usersIdsToFetch")
val response = usersIdsToFetch?.let {
usersAPI.getMultipleUsers(
GetMultipleUsers(it.toList())
)
}
response?.enqueue(object : Callback<List<User>> {
override fun onResponse(
call: Call<List<User>>,
response: Response<List<User>>
) {
response.body()?.let {
rUserRepository.upsert(it.toMutableList())
// conversationRepository.updateUserData(it)
}
}
override fun onFailure(call: Call<List<User>>, t: Throwable) {
Result.retry()
}
})
return@withContext Result.success()
}
return Result.success()
}
}