0

So I'm pretty new to both Scala and RX. The guy who knew the most, and who actually wrote this code, just left, and I'm not sure what's going on. This construct is all over his code and I'm not really clear what its doing:

def foo(List[Long]) : Observable[Unit] =
  Observable {
    subscriber => {
      do some stuff
      subscriber.onNext()
      subscriber.onCompleted()
    }

I mostly get do some stuff, and the calls to subscriber. What I don't get is, where does subscriber come from? Does subscriber => { instantiate the subscriber? What does Observable { subscriber => { ... } } do/mean?

Jeff Barger
  • 1,241
  • 1
  • 13
  • 19

2 Answers2

1

If you take a look at the Observable companion object documentation, you will see an apply method that takes a function of type (Subscriber[T]) ⇒ Unit. So, when you call Observable{withSomeLambda}, then this is the same as calling Observable.apply{withSomeLambda}

And, if you go all the way to the source code you will see that this is really returning

toScalaObservable(rx.Observable.create(f))

where f is the lambda that you passed in.

So, subscriber is just the parameter of the lambda. It is passed in by the caller of that function.

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
1

This code is creating a new Observable as described here.

Basically when a downstream component subscribes to this stream, this callback is called. In the callback we determine when we, as a data source, will call onNext(v: T) which is how we pass each element we are generating to them, and when we will call onCompleted() which is how we tell the subscriber that we are done sending data.

Once you have created an Observable you can start calling Observable operators, which will either result in another, compound Observable, or will result in a terminating condition which will end the process, and generally result in a final result for the flow (often a collection or aggregate value).

You don't use the List in your question, but normally if you wanted to make a reactive stream out of a list you would call Observable.from().

PS: I think this is RxJava code.

Rich Henry
  • 1,837
  • 15
  • 25