Search code examples
androidkotlinandroid-roomrx-java2

Insert a List Into Room Database Using RxJava


I have a list of Items I want to map and then insert into a Room table:

Room

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(vararg projectLocal: ProjectLocal): Completable

The FIRST approach to save data:

Observable.fromIterable(remoteProjects)
            .map { project ->
                ...
                mProjectMapper.mapRemoteToLocal(project)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe {
                mProjectRepository.saveProject(it)
            }

As you may see I'm observing on -> main thread and subscribing on -> io

The Second approach to save data:

remoteProjects.forEach { remote ->
                ...
                val project = mProjectMapper.mapRemoteToLocal(remote)
                mProjectRepository.saveProject(project)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe()
            }

Which one makes more sense? Is there any better way to save all this data inside a Room database using RxJava?


Solution

  • I think this is what @Mwasz means:

    Observable.fromIterable(remoteProjects)
            .map { project ->
                mProjectMapper.mapRemoteToLocal(project)
            }
            .toList()
            .flatMapCompletable {
                mProjectRepository.saveProject(it)
                    .subscribeOn(Schedulers.io())
            }
            .subscribe()
    

    You could also use reduce or collect instead of toList but toList() is the simplest.