Angelina
Angelina

Reputation: 1583

RxJava/Kotlin Observable method call chain - how to terminate?

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) }
        }
}

Upvotes: 3

Views: 1015

Answers (1)

Ahmed Ashraf
Ahmed Ashraf

Reputation: 2835

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

Upvotes: 2

Related Questions