Debu
Debu

Reputation: 615

Sync methods using rxjava

I have these following scenarios -

  1. Say I have 2 async callback(imagine I am calling 2 diff apis) methods callback1(Data d1) and callback2(Data d2), based on d1 and d2 (i.e when both the callback methods are being called)I have to call a method say setupUI(), How to efficiently do that using RxJava
  2. There are two viewpagers v1 and v2 which needs to be synced, i.e on v1 pagechange v2 will also change its current page (indices will be the same) and vice-versa, using Rxjava

Upvotes: 0

Views: 375

Answers (1)

bellol
bellol

Reputation: 91

Try putting subjects in the callbacks to convert them into rx streams.

You can then zip the two subjects up and subscribe to the zipped observable to get the result of both callbacks at the same time

Example: lets make two subjects

PublishSubject<Data> subject1 = PublishSubject.create();
PublishSubject<Data> subject2 = PublishSubject.create();

We can use these to convert our callbacks into something we can subscribe to like this:

public void callback1(Data d1) {
    subject1.onNext(d1);
}

public void callback2(Data d2) {
    subject2.onNext(d2);
}

Now we can get the output when they both emit something like this:

class DataDto {
    Data data1;
    Data data2;

    DataDto(Data data1, Data data2) {
        this.data1 = data1;
        this.data2 = data2;
    }
}

public void main() {
    Observable.zip(subject1, subject2, new BiFunction<Data, Data, DataDto>() {
        @Override
        public DataDto apply(@NonNull Data data1, @NonNull Data data2) throws Exception {
            return new DataDto(data1, data2);
        }
    }).subscribe(new Consumer<DataDto>() {
        @Override
        public void accept(@NonNull DataDto dataDto) throws Exception {
            //do something
        }
    });
}

What zip does is that it waits until both streams have emitted, then emits that as one item.

Here we made a DataDto which contains both data1 and data2

Hope this helps

Upvotes: 1

Related Questions