Android Studio 3.1 RC 2
kotlin 1.2.30
The signature of the fetchMessage in Java
Single<Response> fetchMessage(final String Id);
The kotlin code
fun translate(Id: String): Completable {
return repository.fetchMessage(Id)
.flatMap {
Single.fromCallable<State>({
update(messageId, it, State.COMPLETED)
State.COMPLETED
})
}
.onErrorReturn({
update(Id, null, State.ERROR)
State.ERROR
})
.toCompletable()
}
The method I want to run before fetchMessage
fun insertMessage(Id: String): Completable {
return Completable.fromCallable {
insert(Id, State.IDLE)
}
}
I want the insertMessage e to somehow run before the fetchMessage. I was thinking of using concatMap but not sure how to combine the translate and insertMessage. So that the insertMessage will run first then once completed the translate will run.
Many thanks for any suggestions,
Update solution 1 using startWith(..):
By changing the return to Single for the translate method. I have done like this:
fun translate(Id: String): Single<State> {
return repository.fetchMessage(Id)
.flatMap {
Single.fromCallable<State>({
update(messageId, it, State.COMPLETED)
State.COMPLETED
})
}
.onErrorReturn({
update(Id, null, State.ERROR)
State.ERROR
})
}
Then I can have a method to do the following insertMessage(..) -> translate(..):
translate(Id).toCompletable().startWith(insertMessage(id, State.IDLE))
Would that be an ideal solution?
Update solution 2 using concatWith(..):
My returning a Observable and calling toObservable() in the chain.
fun translate(Id: String): Observable<State> {
return repository.fetchMessage(Id)
.flatMap {
Single.fromCallable<State>({
update(messageId, it, State.COMPLETED)
State.COMPLETED
})
}
.onErrorReturn({
update(Id, null, State.ERROR)
State.ERROR
})
.toObservable()
}
And I can use concatWith so the sequence would be insertMessage(..) -> translate(..):
translate(Id).toCompletable().concatWith(insertMessage(id, State.IDLE).toObservable())
.toCompletable()
Are these correct solutions?