Search code examples
javarx-javareactivex

reactivex java creating a custom observer that emits events at some random time in the future


I am trying to figure out how to create an async observer and trigger/emit events at some time in the future without rebuilding the observable and the subscriber list.

Looking for something like:

MyAsyncObservable o = new MyAsyncObservable();

o.subscribe(s);
o.subscribe(s2);
while(scanner.hasNext()){
  o.emit(scanner.nextInt()); // emit T to subscribers.
}

Where MyAsyncObservable could just be a Observable.fromAsync(emitter,buffermode)

instead of

while(scanner.hasNext(){
  Observable<Integer> o = Observable.just(scanner.nextInt());
  o.subscribe(s);
  o.subscribe(s2);
}

Solution

  • If your observable is cold, just use .delay(); see f.e. this:

    Observable.just("Hello!").delay(10, TimeUnit.SECONDS).subscribe(System.out::println);
    

    If it's a hot observable, just add a buffer (assuming you don't expect more than 10 emissions in 10 seconds:

    Observable
      .just("Hello!")
      .onBackpressureBuffer(10)
      .delay(10, TimeUnit.SECONDS)
      .subscribe(System.out::println);
    

    Edit: Oh, I see - you want a Subject - Either PublishSubject or BehaviorSubject. Create them and feed them data via the usual onNext/onComplete/onError.