I'm using RxJava3 and I have the following code setup where I want to emit an item in the middle, between the first and second flowable. Is there a way to do it?
firstFlowable.firstElement()
//I want to emit an item here
.flatMap { secondFlowable.firstElement() }
The reason I want to do this is because after firstFlowable
initializes there is a long period of time until the secondFlowable
initializes and I want to notify the UI with a message that there the operation has started and I'm waiting on the data computation from secondFlowable
.
I tried to use startWithItem
, but that initializes my whole chain at the beginning, but I want to emit only after firstFlowable
produces its first value.
You could use merge to inject a value, then act based on the value type. In case secondFlowable
finishes immediately, you may want to avoid displaying the string after all via takeUntil
.
firstFlowable.firstElement()
.flatMap(v ->
Maybe.<Object>merge(
secondFlowable.firstElement(),
Maybe.just("Second in progress")
)
)
.takeUntil(v -> !(v instanceof String))
.observeOn(mainThread())
.subscribe(v -> {
if (v instanceof String) {
// display message here
} else {
// cast and display results of second
}
});