1
votes

I'm relatively new on RxJava2 and I'm getting some weird behaviors, so it's likely that I'm using the tool on the wrong way.

It's a fairly big project, but I've separated the snippet below as a minimum reproducible code:

Observable
  .interval(333, TimeUnit.MILLISECONDS)
  .flatMap(new Function<Long, ObservableSource<Integer>>() {
    private Subject<Integer> s = PublishSubject.create();
    private int val = 0;

    @Override public ObservableSource<Integer> apply(Long aLong) throws Exception {
      val++;
      s.onNext(val);
      return s;
      }
    })
  .subscribe(new Consumer<Integer>() {
    @Override public void accept(Integer integer) throws Exception {
      Log.w("value: %s", integer);
     }
  });

This code simulates events from my rx-stream using an .interval and a flatMap receive those events "do some processing" and uses a Subject to push results down the stream.

The stream is an ongoing process which will have several several events.

This minimum code is silly because I'm pushing only on the apply callback, but in the real case there're several possible moments that a push can happen and the number of events being received during apply is not the same amount that will be sent via the Subject.

What I expected to see with this code is:

value: 2  // 1 got skipped because onNext is called before there's a subscriber.
value: 3
value: 4
value: 5
value: 6 ... etc

what I actually got is:

value: 2
value: 3
value: 3 // 3 twice
value: 4
value: 4
value: 4 // 4 repeated 3 times
value: 5
value: 5
value: 5
value: 5 // 5 repeated 4 times
value: 6
value: 6
value: 6
value: 6
value: 6 // 6 repeated 5 times
 ... etc

I've also tried to have an Observable<Integer> o = s.share(); and returning it, or return directly s.share(); with the same results.

I kind of understand why this is happening. The ObservableSource gets subscribed again n again n again so there're more events on every loop.

The question:

How can I achieve my expected behavior?

(in case my expected behavior was not clear, please ask more on the comments)

3
I would try moving private Subject<Integer> s = PublishSubject.create(); on a different scope if I were in you - Blackbelt
@Blackbelt as I said. That's a minimum reproducible code. On the complete code the Function have its own class. - Budius
I can judge what I see and I can't guess what you wrote. - Blackbelt

3 Answers

1
votes

Your PublishSubject is subscribed to multiple times, once per item from interval().

Edit: You will need to pass in a new PublishSubject each time (switch to BehaviorSubject if you'd like to retain the first/last emission); pass that to the long-running process, and ensure that its onComplete is called properly when the long-running process finishes.

1
votes

Edit

After recent comments I could come up with this kind of a solution:

class MyBluetoothClient {
  private PublishSubject<BTLEEvent> statusPublishSubject = PublishSubject.create()

  public Observable<BTLEEvent> getEventObservable() {
    return statusPublishSubject
  }

  private void publishEvent(BTLEEvent event) {
    statusPublishSubject.onNext(event)
  }

  public void doStuff1() {
    // do something that returns:
    publishEvent(BTLEEvent.someEvent1)
  }

  public void doStuff2() {
    // do something else that eventually yields
    publishEvent(BTLEEvent.someEvent2)
  }
}

And you use it in this way:

MyBluetoothClient client = MyBluetoothClient()
client
  .getEventObservable()
  .subscribe( /* */ )

///

client.doStuff1()

/// 

client.doStuff2

Original answer

Will this do?

Observable
  .interval(333, TimeUnit.MILLISECONDS)
  .flatMap(new Function<Long, ObservableSource<Integer>>() {
    private int val = 0;

    @Override public ObservableSource<Integer> apply(Long aLong) throws Exception {
      val++;
      return Observable.just(val);
      }
    })
  .subscribe(new Consumer<Integer>() {
    @Override public void accept(Integer integer) throws Exception {
      Log.w("value: %s", integer);
     }
  });
1
votes

So here is the answer I came up with. I'll mark @Tassos answer as correct as he pointed me out on the right path.

First I need a CachedSubject (a subject that caches items while there's no observers and dispatches them as soon as an observer connects), this is necessary to make sure emissions from inside the apply really gets through. The class mostly wraps a PublishSubject.

class CachedSubject<T> extends Subject<T> {

        private PublishSubject<T> publishSubject = PublishSubject.create();
        private Queue<T> cache = new ConcurrentLinkedQueue<>();

        @Override public boolean hasObservers() {
            return publishSubject.hasObservers();
        }

        @Override public boolean hasThrowable() {
            return publishSubject.hasThrowable();
        }

        @Override public boolean hasComplete() {
            return publishSubject.hasComplete();
        }

        @Override public Throwable getThrowable() {
            return publishSubject.getThrowable();
        }

        @Override protected void subscribeActual(Observer<? super T> observer) {
            while (cache.size() > 0) {
                observer.onNext(cache.remove());
            }
            publishSubject.subscribeActual(observer);
        }

        @Override public void onSubscribe(Disposable d) {
            publishSubject.onSubscribe(d);
        }

        @Override public void onNext(T t) {
            if (hasObservers()) {
                publishSubject.onNext(t);
            } else {
                cache.add(t);
            }
        }

        @Override public void onError(Throwable e) {
            publishSubject.onError(e);
        }

        @Override public void onComplete() {
            publishSubject.onComplete();
        }
    }

then I use this class with a switchMap:

Observable
   .interval(1000, TimeUnit.MILLISECONDS)
   .switchMap(new Function<Long, ObservableSource<Integer>>() {

      private Subject<Integer> s = new CachedSubject<>();
      private int val = 0;

      @Override public ObservableSource<Integer> apply(Long aLong) throws Exception {
         val++;
         s.onNext(val);
         return s;
      }
   })
   .subscribe(new Consumer<Integer>() {
      @Override public void accept(Integer integer) throws Exception {
         Log.w("value: %s", integer);
      }
   });

This effectively allows me to receive any number of events on the apply<T t> method and have only 1 Consumer subscribed to it, receiving all the events from it.