I've been trying to figure this out still new to RXJava and still not liking it, rather use Livedata and coroutines but anyway.. I have this:
Single.just(entity)
.map {
insertDb(it)
return@map it
}
.doOnSubscribe { Timber.d("Updating in database") }
.doOnSuccess { Timber.d("Added row in database") }
.doOnError { Timber.e(it, "Unable to insert object in db") }
fun insertDb(entity: T) {
try {
// basic update or insert database.begingTransaction() and endTransaction()
} catch (e: SQLiteDatabaseLockedException) {}
}
So when the error of DB locked occurs I want to catch it and retry the insert using the Single with a retryWhen(). The examples I read are very convoluted and not quite what I want. And don't worry about the locked DB stuff this is just an example of how I would catch DB errors.
You can use a PublishProcessor
:
val retryProcessor = PublishProcessor.create<Unit>()
Single.just("Entity")
.map { insertDB(it) }
.doOnError { Log.e(TAG, "Error") }
.retryWhen { retryProcessor }
.subscribe { entity -> Log.i(TAG, "Success: $entity") }
Insert to DB:
fun insertDB(entity: String): String {
// Insert to DB
return entity
}
Whenever you want to perform a retry, call onNext
on the PublishProcessor
:
retryProcessor.onNext(Unit)