These are chat archives for ReactiveX/RxJava

12th
Dec 2017
Fyodor Sherstobitov
@fsherstobitov
Dec 12 2017 07:40

Hi everyone! I'm trying to implement REST call caching on Android using RxJava. I have this code:

    override fun loadTasks(): Maybe<List<Task>> {
        Log.d(TAG, "Searching tasks in database")
        return boxJobDao.getAll()
                .map { boxJobs -> boxJobMapper.entityListToTaskList(boxJobs) }
                .switchIfEmpty(syncTasks())
    }

    private fun syncTasks(): Maybe<List<Task>> {
        Log.d(TAG, "Loading tasks from server")
        return api.boxJobs(DEVICE_ID)
                .doOnSuccess({ boxJobDtoList ->
                    Log.d(TAG, "${boxJobDtoList.size} box jobs loaded from server")
                    saveToDb(boxJobDtoList)
                })
                .doOnError({ error -> Log.d(TAG, "Error during tasks loading", error) })
                .map { boxJobDtoList -> boxJobMapper.dtoListToTaskList(boxJobDtoList) }
                .toMaybe()
    }

    private fun saveToDb(boxJobDtoList: List<BoxJobDto>?) {
        Log.d(TAG, "Saving box jobs to database")
        boxJobDtoList?.forEach { boxJobDto ->
            try {
                val boxJob = boxJobMapper.dtoToEntity(boxJobDto)
                boxJobDao.insert(boxJob)
                val barcodeReadList = boxJobDto.barcodeReadDtos?.map { dto -> barcodeReadMapper.dtoToEntity(dto) }
                barcodeReadDao.insertAll(barcodeReadList ?: emptyList())
            } catch (e: Throwable) {
                Log.e(TAG, "Error during box jobs saving", e)
            }
        }
    }

I return the list of tasks from DB if there are any. If no tasks found in DB, I switch to REST API, get tasks from it, save to DB and return them to caller.

The problem is that the code never gets to doOnSuccess callback. Am I doing something wrong?