1

I have nested items in my database like e.g. house - rooms. If I delete a house I also want to delete all rooms, but I do not want to think about this, so the house must know this. So my setup would look something like this:

fun deleteHouse(item: House): Single<House> {
    houseObservable // emits List<House>
        .take(1)
        .map { 
            DBManager.beginTransaction()
            it
        }
        .flatMapIterable { it }
        .flatMapSingle { deleteRoom(it) }
        .toList()
        .map { 
            DBManager.deleteWithoutDependencies(item)
            DBManager.endTransaction()
            item
        }
}

fun deleteRoom(item: Room): Single<Room> {
    roomObservables // emits List<Room>
        .take(1)
        .map { 
            DBManager.beginTransaction()
            it
        }
        .flatMapIterable { it }
        .flatMapSingle { DBManager.deleteWithoutDependencies(item) }
        .toList()
        .map { 
            DBManager.endTransaction()
            item
        }
}

Problem

Every item is deleted on RxComputationThread-1 and every beginTransaction and endTransaction as well, BUT the last endTransaction that finished the deletion of the house.

I need to run all database actions on the same thread, otherwise the database will lock itself out...

Any ideas how to solve this?

Idea

Pass the used Schedular to the functions and use the same in the flatMaps, but is this really necessary to solve this problem?

prom85
  • 16,896
  • 17
  • 122
  • 242
  • Create a single-threaded `Scheduler` and apply `observeOn` just before those `map`s and most likely `subscribeOn` on `deleteWithoutDependencies`. – akarnokd Sep 14 '18 at 07:58
  • I'll try that. Additionally I've created a complete example that fully matches my real use case here: https://github.com/MFlisar/tests/blob/master/app/src/main/java/com/michaelflisar/tests/tests/RxMapTest.kt The weird thing is that the example works perfectly fine - everyting is done on the same thread. Is this just by chance? – prom85 Sep 14 '18 at 08:30
  • I tried using observing on `Schedulers.single()` on the most outer stream AND before each map that begins/ends a transaction and before each map in which an item is deleted from the database and this works. Not using any schedulars midstream and only using `Schedulers.single()` on the outer most stream is not enough. Weird, because in my github demo I can see that ALL maps are executed on the same thread, the one passed to the main streams `observeOn` function... – prom85 Sep 14 '18 at 08:56

0 Answers0