3

I want to implement method to edit a note, save it to local database (cache) and then send it to the server as a POST request. I am learning RxJava and I wanted to create Observable from the note and then apply transformations on it, like to map it to an Entity model and saving. The issue that my method returns Completable and this chain returns Observable<Completable>. How to unwrap the Completable from this Observable which I used only to start RxJava stuff. Each editNote() methods returns a Completable.

 override fun editNote(note: Note): Completable {
    return Observable.just(note)
        .map { mapper.mapToEntity(it) }
        .map { noteEntity ->
            factory.getCacheDataStore().editNote(noteEntity)
                .andThen { factory.getRemoteDataStore().editNote(noteEntity) }
        }
}

=======================================================

UPDATE

Finally, I managed to find "a solution" but I am not sure it is correct :-)

override fun editNote(note: Note): Completable {
    return Observable.just(note)
        .map { mapper.mapToEntity(it) }
        .flatMapCompletable { noteEntity ->
            factory.getCacheDataStore().editNote(noteEntity)
                .andThen { factory.getRemoteDataStore().editNote(noteEntity) }
        }
}
Angelina
  • 1,473
  • 2
  • 16
  • 34

1 Answers1

2

You're looking for flatMapCompletable instead of map, because map just intercepts the stream and maps the emissions to another type, while 'flatMap' (or it's siblings), from the docs:

Transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable.

You can see it's marble diagram in Here

Ahmed Ashraf
  • 2,795
  • 16
  • 25
  • Could you translate that (the difference between map and flatMap) into English please? The Rx docs are written in their own language and are painfully opaque. – Gumby The Green Jul 23 '19 at 17:38
  • 1
    https://stackoverflow.com/questions/22847105/when-do-you-use-map-vs-flatmap-in-rxjava Maybe the usecases of each will help you understand the difference. – Ahmed Ashraf Jul 23 '19 at 21:18