0

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.

Filip
  • 19,269
  • 7
  • 51
  • 60
kemenesendre
  • 165
  • 1
  • 1
  • 11

2 Answers2

0

Maybe you can use concatWith() with take() and skip() for the firstFlowable.

public static void main(String[] args) {
   Flowable<String> firstFlowable = Flowable.just("1st", "2nd", "3rd", "4th", "5th");
   Flowable<String> middleFlowable = Flowable.just("between");
   Flowable<String> secondFlowable = Flowable.just("A", "B", "C", "D");

   firstFlowable.take(1)
                .concatWith(middleFlowable)
                .concatWith(firstFlowable.skip(1))
                .concatWith(secondFlowable)
                .subscribe(System.out::println);

   Flowable.timer(10, SECONDS).blockingSubscribe();  // Just to block the main thread for a while
}

This gives something like that:

1st
between
2nd
3rd
4th
5th
A
B
C
D
ctranxuan
  • 785
  • 5
  • 9
0

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
   }
});
akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • Thank you for the idea. I ended up using only the merge, because I didn't necessarily like the decision made using the type of the item the flowable emits and the business context I'm in doesn't allow for that decision (the code snippet is an abstract of the real need), but the general idea solved my issue. – kemenesendre May 03 '21 at 14:30