Lukasz Guminski
Lukasz Guminski

Reputation: 912

Delaying Rx-java Observable until another Observable completes

It's a beginner's question. I am writing a unit test and I need to make a observable starting after b completed.

Observable<Integer> a = Observable.just(3, 4);
Observable<Integer> b = Observable.just(1, 2);

// TODO code needed here

// It is a is unit test above the line
// ---------------------------
// below is the code of the class being tested

a.forEach(System.out::print);
b.forEach(System.out::print);

What should be the code to have

1234

printed out?

I tried concatWith(), toBlocking() and nothing seems to work. Thanks in advance.

Upvotes: 2

Views: 816

Answers (3)

paul
paul

Reputation: 13471

You could subscribe b and then in the onComplete of observable b subscribe a. In both observable you have to implement on the onNext action the print of the emitted item.

    Observable<Integer> a = Observable.just(3, 4);
    Observable<Object> b = Observable.just(1, 2);
    b.subscribe(System.out::print, System.out::println, () -> a.subscribe(System.out::print));

Upvotes: 0

Lukasz Guminski
Lukasz Guminski

Reputation: 912

@Enigmativity's answer translated to Java

Observable<Integer> a0 = Observable.just(3, 4);
Observable<Integer> b0 = Observable.just(1, 2);
PublishSubject<Integer> a = PublishSubject.<Integer>create();
Observable<Integer> b = b0.finallyDo(() -> {
    a0.subscribe(a);
});
a.forEach(System.out::print);
b.forEach(System.out::print); 

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117027

I apologize, but I'm a C# developer and not Java at all.

Here's one way to do it in C#. I assume it can be easily transcoded:

IObservable<int> a0 = new [] { 3, 4 }.ToObservable();
IObservable<int> b0 = new [] { 1, 2 }.ToObservable();

var a = new Subject<int>();
var b = b0.Finally(() => a0.Subscribe(a));

a.Subscribe(Console.WriteLine);
b.Subscribe(Console.WriteLine);

This results in:

1
2
3
4

Upvotes: 1

Related Questions