

ReactiveX
=========

  ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences. 


 It extends [the observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O. 




| Observables fill the gap by being the ideal way to access asynchronous sequences of multiple items |
| --- |
|  | single items | multiple items |
| --- | --- | --- |
| synchronous | `T getData()` | `Iterable<T> getData()` |
| asynchronous | `Future<T> getData()` | `Observable<T> getData()` |

  It is sometimes called “functional reactive programming” but this is a misnomer. ReactiveX may be functional, and it may be reactive, but “functional reactive programming” is a different animal. One main point of difference is that functional reactive programming operates on values that change *continuously* over time, while ReactiveX operates on *discrete* values that are emitted over time. (See [Conal Elliott’s work for more-precise information on functional reactive programming](https://github.com/conal/essence-and-origins-of-frp).) 

 Why Use Observables?
--------------------

  The ReactiveX Observable model allows you to treat streams of asynchronous events with the same sort of simple, composable operations that you use for collections of data items like arrays. It frees you from tangled webs of callbacks, and thereby makes your code more readable and less prone to bugs. 

 Observables Are Composable
--------------------------

  Techniques like [Java Futures](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html) are straightforward to use for [a single level of asynchronous execution](https://gist.github.com/4670979) but they start to add [non-trivial complexity](https://gist.github.com/4671081) when they’re nested. 


 It is [difficult to use Futures to optimally compose conditional asynchronous execution flows](https://gist.github.com/4671081#file-futuresb-java-L163) (or impossible, since latencies of each request vary at runtime). This [can be done](http://www.amazon.com/gp/product/0321349601?ie=UTF8&tag=none0b69&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321349601), of course, but it quickly becomes complicated (and thus error-prone) or it prematurely blocks on `Future.get()`, which eliminates the benefit of asynchronous execution. 


 ReactiveX Observables, on the other hand, are *intended* for [composing flows and sequences of asynchronous data](https://github.com/Netflix/RxJava/wiki/How-To-Use#composition). 

 Observables Are Flexible
------------------------

  ReactiveX Observables support not just the emission of single scalar values (as Futures do), but also of sequences of values or even infinite streams. `Observable` is a single abstraction that can be used for any of these use cases. An Observable has all of the flexibility and elegance associated with its mirror-image cousin the Iterable. 

 

| An Observable is the asynchronous/push [“dual”](http://en.wikipedia.org/wiki/Dual_(category_theory)) to the synchronous/pull Iterable |
| --- |
| event | Iterable (pull) | Observable (push) |
| retrieve data | `T next()` | `onNext(T)` |
| discover error | throws `Exception` | `onError(Exception)` |
| complete | `!hasNext()` | `onCompleted()` |

 Observables Are Less Opinionated
--------------------------------

  ReactiveX is not biased toward some particular source of concurrency or asynchronicity. Observables can be implemented using thread-pools, event loops, non-blocking I/O, actors (such as from Akka), or whatever implementation suits your needs, your style, or your expertise. Client code treats all of its interactions with Observables as asynchronous, whether your underlying implementation is blocking or non-blocking and however you choose to implement it. 




| How is this Observable implemented? |
| --- |
| `public Observable<data> getData();` |
| From the Observer’s point of view, it doesn’t matter! |
| --- |
| * does it work synchronously on the same thread as the caller?
* does it work asynchronously on a distinct thread?
* does it divide its work over multiple threads that may return data to the caller in any order?
* does it use an Actor (or multiple Actors) instead of a thread pool?
* does it use NIO with an event-loop to do asynchronous network access?
* does it use an event-loop to separate the work thread from the callback thread?
 |

  And importantly: with ReactiveX you can later change your mind, and radically change the underlying nature of your Observable implementation, without breaking the consumers of your Observable. 

 Callbacks Have Their Own Problems
---------------------------------

  Callbacks solve the problem of premature blocking on `Future.get()` by not allowing anything to block. They are naturally efficient because they execute when the response is ready. 


 But as with Futures, while callbacks are easy to use with a single level of asynchronous execution, [with nested composition they become unwieldy](https://gist.github.com/4677544). 

 ReactiveX Is a Polyglot Implementation
--------------------------------------

  ReactiveX is currently implemented in a variety of languages, in ways that respect those languages’ idioms, and more languages are being added at a rapid clip. 

 Reactive Programming
--------------------

  ReactiveX provides [a collection of operators](documentation/operators) with which you can filter, select, transform, combine, and compose Observables. This allows for efficient execution and composition. 


 You can think of the Observable class as a “push” equivalent to [Iterable](http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html), which is a “pull.” With an Iterable, the consumer pulls values from the producer and the thread blocks until those values arrive. By contrast, with an Observable the producer pushes values to the consumer whenever values are available. This approach is more flexible, because values can arrive synchronously or asynchronously. 




| Example code showing how similar high-order functions can be applied to an Iterable and an Observable |
| --- |
| `Iterable` | `Observable` |
| 
```
getDataFromLocalMemory()
  .skip(10)
  .take(5)
  .map({ s -> return s + " transformed" })
  .forEach({ println "next => " + it })
```
 | 
```
getDataFromNetwork()
  .skip(10)
  .take(5)
  .map({ s -> return s + " transformed" })
  .subscribe({ println "onNext => " + it })
```
 |

  The Observable type adds two missing semantics to [the Gang of Four’s Observer pattern](http://en.wikipedia.org/wiki/Observer_pattern), to match those that are available in the Iterable type: 


1. the ability for the producer to signal to the consumer that there is no more data available (a foreach loop on an Iterable completes and returns normally in such a case; an Observable calls its observer’s `onCompleted` method)
2. the ability for the producer to signal to the consumer that an error has occurred (an Iterable throws an exception if an error takes place during iteration; an Observable calls its observer’s `onError` method)


 With these additions, ReactiveX harmonizes the Iterable and Observable types. The only difference between them is the direction in which the data flows. This is very important because now any operation you can perform on an Iterable, you can also perform on an Observable. 



 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/intro.html>

Observable
==========

  In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so. 


 This page explains what the reactive pattern is and what Observables and observers are (and how observers subscribe to Observables). Other pages show how you use [the variety of Observable operators](operators) to link Observables together and change their behaviors. 

  This documentation accompanies its explanations with “marble diagrams.” Here is how marble diagrams represent Observables and transformations of Observables:

 ![](http://reactivex.io/assets/operators/legend.png)  #### See Also

 * [Single](single) — a specialized version of an Observable that emits only a single item
* [Rx Workshop: Introduction](http://channel9.msdn.com/Series/Rx-Workshop/Rx-Workshop-Introduction)
* [Introduction to Rx: IObservable](http://www.introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html#IObservable)
* [Mastering observables](http://docs.couchbase.com/developer/java-2.0/observables.html) (from the Couchbase Server documentation)
* [2 minute introduction to Rx](https://medium.com/@andrestaltz/2-minute-introduction-to-rx-24c8ca793877) by Andre Staltz (“Think of an Observable as an asynchronous immutable array.”)
* [Introducing the Observable](https://egghead.io/lessons/javascript-introducing-the-observable) by Jafar Husain (JavaScript Video Tutorial)
* [Observable object](http://xgrommx.github.io/rx-book/content/observable/index.html) (RxJS) by Dennis Stoyanov
* [Turning a callback into an Rx Observable](https://afterecho.uk/blog/turning-a-callback-into-an-rx-observable.html) by @afterecho

 Background
----------

  In many software programming tasks, you more or less expect that the instructions you write will execute and complete incrementally, one-at-a-time, in order as you have written them. But in ReactiveX, many instructions may execute in parallel and their results are later captured, in arbitrary order, by “observers.” Rather than *calling* a method, you define a mechanism for retrieving and transforming the data, in the form of an “Observable,” and then *subscribe* an observer to it, at which point the previously-defined mechanism fires into action with the observer standing sentry to capture and respond to its emissions whenever they are ready. 


 An advantage of this approach is that when you have a bunch of tasks that are not dependent on each other, you can start them all at the same time rather than waiting for each one to finish before starting the next one — that way, your entire bundle of tasks only takes as long to complete as the longest task in the bundle. 


 There are many terms used to describe this model of asynchronous programming and design. This document will use the following terms: An observer subscribes to an Observable. An Observable emits items or sends notifications to its observers by calling the observers’ methods. 


 In other documents and other contexts, what we are calling an “observer” is sometimes called a “subscriber,” “watcher,” or “reactor.” This model in general is often referred to as the [“reactor pattern”](http://en.wikipedia.org/wiki/Reactor_pattern). 

 Establishing Observers
----------------------

  This page uses Groovy-like pseudocode for its examples, but there are ReactiveX implementations in many languages. 


 In an ordinary method call — that is, *not* the sort of asynchronous, parallel calls typical in ReactiveX — the flow is something like this: 


1. Call a method.
2. Store the return value from that method in a variable.
3. Use that variable and its new value to do something useful.

  Or, something like this: 

 
```
// make the call, assign its return value to `returnVal`
returnVal = someMethod(itsParameters);
// do something useful with returnVal
```
  In the asynchronous model the flow goes more like this: 


1. Define a method that does something useful with the return value from the asynchronous call; this method is part of the *observer*.
2. Define the asynchronous call itself as an *Observable*.
3. Attach the observer to that Observable by *subscribing* it (this also initiates the actions of the Observable).
4. Go on with your business; whenever the call returns, the observer’s method will begin to operate on its return value or values — the *items* emitted by the Observable.

  Which looks something like this: 

 
```
// defines, but does not invoke, the Subscriber's onNext handler
// (in this example, the observer is very simple and has only an onNext handler)
def myOnNext = { it -> do something useful with it };
// defines, but does not invoke, the Observable
def myObservable = someObservable(itsParameters);
// subscribes the Subscriber to the Observable, and invokes the Observable
myObservable.subscribe(myOnNext);
// go on about my business
```
 onNext, onCompleted, and onError
--------------------------------

  [The `Subscribe` method](operators/subscribe) is how you connect an observer to an Observable. Your observer implements some subset of the following methods: 

  `onNext` An Observable calls this method whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable. `onError` An Observable calls this method to indicate that it has failed to generate the expected data or has encountered some other error. It will not make further calls to `onNext` or `onCompleted`. The `onError` method takes as its parameter an indication of what caused the error. `onCompleted` An Observable calls this method after it has called `onNext` for the final time, if it has not encountered any errors.   By the terms of [the Observable contract](contract), it may call `onNext` zero or more times, and then may follow those calls with a call to either `onCompleted` or `onError` but not both, which will be its last call. By convention, in this document, calls to `onNext` are usually called “emissions” of items, whereas calls to `onCompleted` or `onError` are called “notifications.” 


 A more complete `subscribe` call example looks like this: 

 
```
def myOnNext     = { item -> /* do something useful with item */ };
def myError      = { throwable -> /* react sensibly to a failed call */ };
def myComplete   = { /* clean up after the final response */ };
def myObservable = someMethod(itsParameters);
myObservable.subscribe(myOnNext, myError, myComplete);
// go on about my business
```
 #### See Also

 * [Introduction to Rx: IObserver](http://www.introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html#IObserver)

 Unsubscribing
-------------

  In some ReactiveX implementations, there is a specialized observer interface, `Subscriber`, that implements an `unsubscribe` method. You can call this method to indicate that the Subscriber is no longer interested in any of the Observables it is currently subscribed to. Those Observables can then (if they have no other interested observers) choose to stop generating new items to emit. 


 The results of this unsubscription will cascade back through the chain of operators that applies to the Observable that the observer subscribed to, and this will cause each link in the chain to stop emitting items. This is not guaranteed to happen immediately, however, and it is possible for an Observable to generate and attempt to emit items for a while even after no observers remain to observe these emissions. 

 Some Notes on Naming Conventions
--------------------------------

  Each language-specific implementation of ReactiveX has its own naming quirks. There is no canonical naming standard, though there are many commonalities between implementations. 


 Furthermore, some of these names have different implications in other contexts, or seem awkward in the idiom of a particular implementing language. 


 For example there is the `on*Event*` naming pattern (e.g. `onNext`, `onCompleted`, `onError`). In some contexts such names would indicate methods by means of which event handlers are *registered*. In ReactiveX, however, they name the event handlers themselves. 

 “Hot” and “Cold” Observables
----------------------------

  When does an Observable begin emitting its sequence of items? It depends on the Observable. A “hot” Observable may begin emitting items as soon as it is created, and so any observer who later subscribes to that Observable may start observing the sequence somewhere in the middle. A “cold” Observable, on the other hand, waits until an observer subscribes to it before it begins to emit items, and so such an observer is guaranteed to see the whole sequence from the beginning. 


 In some implementations of ReactiveX, there is also something called a “Connectable” Observable. Such an Observable does not begin emitting items until its [Connect](operators/connect) method is called, whether or not any observers have subscribed to it. 

 Composition via Observable Operators
------------------------------------

  Observables and observers are only the start of ReactiveX. By themselves they’d be nothing more than a slight extension of the standard observer pattern, better suited to handling a sequence of events rather than a single callback. 


 The real power comes with the “reactive extensions” (hence “ReactiveX”) — operators that allow you to transform, combine, manipulate, and work with the sequences of items emitted by Observables. 


 These Rx operators allow you to compose asynchronous sequences together in a declarative manner with all the efficiency benefits of callbacks but without the drawbacks of nesting callback handlers that are typically associated with asynchronous systems. 


 This documentation groups information about [the various operators](operators#alphabetical) and examples of their usage into the following pages: 


 [Creating Observables](operators#creating) 
`Create`, `Defer`, `Empty`/`Never`/`Throw`, `From`, `Interval`, `Just`, `Range`, `Repeat`, `Start`, and `Timer`
 [Transforming Observable Items](operators#transforming) 
`Buffer`, `FlatMap`, `GroupBy`, `Map`, `Scan`, and `Window`
 [Filtering Observables](operators#filtering) 
`Debounce`, `Distinct`, `ElementAt`, `Filter`, `First`, `IgnoreElements`, `Last`, `Sample`, `Skip`, `SkipLast`, `Take`, and `TakeLast`
 [Combining Observables](operators#combining) 
`And`/`Then`/`When`, `CombineLatest`, `Join`, `Merge`, `StartWith`, `Switch`, and `Zip`
 [Error Handling Operators](operators#error) 
`Catch` and `Retry`
 [Utility Operators](operators#utility) 
`Delay`, `Do`, `Materialize`/`Dematerialize`, `ObserveOn`, `Serialize`, `Subscribe`, `SubscribeOn`, `TimeInterval`, `Timeout`, `Timestamp`, and `Using`
 [Conditional and Boolean Operators](operators#conditional) 
`All`, `Amb`, `Contains`, `DefaultIfEmpty`, `SequenceEqual`, `SkipUntil`, `SkipWhile`, `TakeUntil`, and `TakeWhile`
 [Mathematical and Aggregate Operators](operators#mathematical) 
`Average`, `Concat`, `Count`, `Max`, `Min`, `Reduce`, and `Sum`
 [Converting Observables](operators#conversion) `To` [Connectable Observable Operators](operators#connectable) 
`Connect`, `Publish`, `RefCount`, and `Replay`
 [Backpressure Operators](operators/backpressure) a variety of operators that enforce particular flow-control policies   These pages include information about some operators that are not part of the core of ReactiveX but are implemented in one or more of language-specific implementations and/or optional modules. 

 Chaining Operators
------------------

  Most operators operate on an Observable and return an Observable. This allows you to apply these operators one after the other, in a chain. Each operator in the chain modifies the Observable that results from the operation of the previous operator. 


 There are other patterns, like the Builder Pattern, in which a variety of methods of a particular class operate on an item of that same class by modifying that object through the operation of the method. These patterns also allow you to chain the methods in a similar way. But while in the Builder Pattern, the order in which the methods appear in the chain does not usually matter, with the Observable operators *order matters*. 


 A chain of Observable operators do not operate independently on the original Observable that originates the chain, but they operate *in turn*, each one operating on the Observable generated by the operator immediately previous in the chain. 



 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/observable.html>

Subscribe
=========

 
> operate upon the emissions and notifications from an Observable

  The Subscribe operator is the glue that connects an observer to an Observable. In order for an observer to see the items being emitted by an Observable, or to receive error or completed notifications from the Observable, it must first subscribe to that Observable with this operator. 


 A typical implementation of the Subscribe operator may accept one to three methods (which then constitute the observer), or it may accept an object (sometimes called an `Observer` or `Subscriber`) that implements the interface which includes those three methods: 


 `onNext` An Observable calls this method whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable. `onError` An Observable calls this method to indicate that it has failed to generate the expected data or has encountered some other error. This stops the Observable and it will not make further calls to `onNext` or `onCompleted`. The `onError` method takes as its parameter an indication of what caused the error (sometimes an object like an Exception or Throwable, other times a simple string, depending on the implementation). `onCompleted` An Observable calls this method after it has called `onNext` for the final time, if it has not encountered any errors.   An Observable is called a “cold” Observable if it does not begin to emit items until an observer has subscribed to it; an Observable is called a “hot” Observable if it may begin emitting items at any time, and a subscriber may begin observing the sequence of emitted items at some point after its commencement, missing out on any items emitted previously to the time of the subscription. 

 #### See Also

 * [Do](do)
* [Introduction to Rx: IObserver](http://www.introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html#IObserver)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `BlockingObservable.forEach forEach subscribe`

     RxGroovy implements several variants of `subscribe`. 


 If you pass it no parameters, it will trigger a subscription to the underlying Observable, but will ignore its emissions and notifications. This will activate a cold Observable. 


 You can also pass it between one and three functions; these will be interpreted as follows: 

 1. `onNext`
2. `onNext` and `onError`
3. `onNext`, `onError`, and `onCompleted`

  Finally, you can pass it an object that implements either of the `Observer` or `Subscriber` interfaces. The `Observer` interface consists of the three previously-described “`on`” methods. The `Subscriber` interface implements these also, and adds a number of additional methods that facilitate reactive pull backpressure and that permit the Subscriber to unsubscribe to an Observable before it completes. 


 The call to `subscribe` returns an object that implements the `Subscription` interface. This interface includes the `unsubscribe` method that you can call at any time to sever the subscription that `subscribe` established between the Observable and the observer (or the methods that stand in for the observer). 

 * Javadoc: [`subscribe()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe())
* Javadoc: [`subscribe(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.functions.Action1))
* Javadoc: [`subscribe(Action1,Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.functions.Action1,%20rx.functions.Action1))
* Javadoc: [`subscribe(Action1,Action1,Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.functions.Action1,%20rx.functions.Action1,%20rx.functions.Action0))
* Javadoc: [`subscribe(Observer)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.Observer))
* Javadoc: [`subscribe(Subscriber)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.Subscriber))

  The `forEach` operators are simpler versions of `subscribe`. You can pass them between one and three functions, which will be interpreted as follows: 

 1. `onNext`
2. `onNext` and `onError`
3. `onNext`, `onError`, and `onCompleted`

  Unlike `subscribe`, `forEach` does not return an object with which you can cancel the subscription. Nor do you have the option of passing a parameter that has this capability. So you should only use this operator if you definitely need to operate on all of the emissions and notifications from the Observable. 

 * Javadoc: [`forEach(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#forEach(rx.functions.Action1))
* Javadoc: [`forEach(Action1,Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#forEach(rx.functions.Action1,%20rx.functions.Action1))
* Javadoc: [`forEach(Action1,Action1,Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#forEach(rx.functions.Action1,%20rx.functions.Action1,%20rx.functions.Action0))

  ![forEach](http://reactivex.io/documentation/operators/images/B.forEach.png)  There is also a `BlockingObservable` method called `forEach` that is somewhat similar. In order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 `BlockingObservable.forEach` takes a single function as its parameter, and this function behaves much like an `onNext` function in the subscription to an ordinary Observable. The `forEach` operator itself blocks until the `BlockingObservable` completes, and it is by unblocking, rather than by calling a callback function, that it indicates that it is complete. If it encounters an error it will throw a `RuntimeException` (rather than calling an analogue to the `onError` callback). 

 * Javadoc: [BlockingObservable.forEach(Action1)](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#forEach(rx.functions.Action1))
       ###  RxJava 1․x `BlockingObservable.forEach forEach subscribe`

     RxJava implements several variants of `subscribe`. 


 If you pass it no parameters, it will trigger a subscription to the underlying Observable, but will ignore its emissions and notifications. This will activate a cold Observable. 


 You can also pass it between one and three functions; these will be interpreted as follows: 

 1. `onNext`
2. `onNext` and `onError`
3. `onNext`, `onError`, and `onCompleted`

  Finally, you can pass it an object that implements either of the `Observer` or `Subscriber` interfaces. The `Observer` interface consists of the three previously-described “`on`” methods. The `Subscriber` interface implements these also, and adds a number of additional methods that facilitate reactive pull backpressure and that permit the Subscriber to unsubscribe to an Observable before it completes. 


 The call to `subscribe` returns an object that implements the `Subscription` interface. This interface includes the `unsubscribe` method that you can call at any time to sever the subscription that `subscribe` established between the Observable and the observer (or the methods that stand in for the observer). 

 * Javadoc: [`subscribe()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe())
* Javadoc: [`subscribe(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.functions.Action1))
* Javadoc: [`subscribe(Action1,Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.functions.Action1,%20rx.functions.Action1))
* Javadoc: [`subscribe(Action1,Action1,Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.functions.Action1,%20rx.functions.Action1,%20rx.functions.Action0))
* Javadoc: [`subscribe(Observer)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.Observer))
* Javadoc: [`subscribe(Subscriber)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribe(rx.Subscriber))

  The `forEach` operators are simpler versions of `subscribe`. You can pass them between one and three functions, which will be interpreted as follows: 

 1. `onNext`
2. `onNext` and `onError`
3. `onNext`, `onError`, and `onCompleted`

  Unlike `subscribe`, `forEach` does not return an object with which you can cancel the subscription. Nor do you have the option of passing a parameter that has this capability. So you should only use this operator if you definitely need to operate on all of the emissions and notifications from the Observable. 

 * Javadoc: [`forEach(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#forEach(rx.functions.Action1))
* Javadoc: [`forEach(Action1,Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#forEach(rx.functions.Action1,%20rx.functions.Action1))
* Javadoc: [`forEach(Action1,Action1,Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#forEach(rx.functions.Action1,%20rx.functions.Action1,%20rx.functions.Action0))

  ![forEach](http://reactivex.io/documentation/operators/images/B.forEach.png)  There is also a `BlockingObservable` method called `forEach` that is somewhat similar. In order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 `BlockingObservable.forEach` takes a single function as its parameter, and this function behaves much like an `onNext` function in the subscription to an ordinary Observable. The `forEach` operator itself blocks until the `BlockingObservable` completes, and it is by unblocking, rather than by calling a callback function, that it indicates that it is complete. If it encounters an error it will throw a `RuntimeException` (rather than calling an analogue to the `onError` callback). 

 * Javadoc: [BlockingObservable.forEach(Action1)](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#forEach(rx.functions.Action1))
       ###  RxJS `forEach subscribe subscribeOnCompleted subscribeOnError subscribeOnNext`

     In RxJS, you can subscribe to an Observable in two ways: 

 1. subscribe a single function to either the `onNext`, the `onCompleted`, or `onError` notifications from an Observable, with `subscribeOnNext`, `subscribeOnCompleted`, or `subscribeOnError` respectively
2. subscribe by passing zero to three individual functions, or an object that implements those three functions, into either the `subscribe` or `forEach` operator (those operators behave identically).

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 3)

var subscription = source.subscribeOnNext(
  function (x) {
    console.log('Next: %s', x);
  });
```
 
```
Next: 0
Next: 1
Next: 2
```
 
```
var source = Rx.Observable.range(0, 3);

var subscription = source.subscribeOnCompleted(
  function () {
    console.log('Completed');
  });
```
 
```
Completed
```
 
```
var source = Rx.Observable.throw(new Error());

var subscription = source.subscribeOnError(
  function (err) {
    console.log('Error: %s', err);
  });
```
 
```
Error: Error
```
 
```
var observer = Rx.Observer.create(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });

var source = Rx.Observable.range(0, 3)

var subscription = source.subscribe(observer);
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
 
```
var source = Rx.Observable.range(0, 3)

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
  The functions described in this section are all found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `subscribe`

       RxPHP implements this operator as `subscribe`. 

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/subscribe.html>

Single
======

  RxJava (and its derivatives like RxGroovy & RxScala) has developed an [Observable](observable) variant called “Single.” 


 A Single is something like an Observable, but instead of emitting a series of values — anywhere from none at all to an infinite number — it always either emits one value or an error notification. 


 For this reason, instead of subscribing to a Single with the three methods you use to respond to notifications from an Observable (onNext, onError, and onCompleted), you only use two methods to subscribe: 


 onSuccess a Single passes this method the sole item that the Single emits onError a Single passes this method the Throwable that caused the Single to be unable to emit an item 
 A Single will call only one of these methods, and will only call it once. Upon calling either method, the Single terminates and the subscription to it ends. 

 Composition via Single Operators
--------------------------------

  Like Observables, Singles can be manipulated by means of a variety of operators. Some operators also allow for an interface between the Observable world and the Single world so that you can mix the two varieties: 

 

| operator | returns | description |
| --- | --- | --- |
| compose | Single | allows you create a custom operator |
| concat and concatWith | Observable | concatenates the items emitted by multiple Singles as Observable emissions |
| create | Single | create a Single from scratch by calling subscriber methods explicitly |
| delay | Single | move the emission of an item from a Single forward in time |
| doOnError | Single | returns a Single that also calls a method you specify when it calls onError |
| doOnSuccess | Single | returns a Single that also calls a method you specify when it calls onSuccess |
| error | Single | returns a Single that immediately notifies subscribers of an error |
| flatMap | Single | returns a Single that is the result of a function applied to an item emitted by a Single |
| flatMapObservable | Observable | returns an Observable that is the result of a function applied to an item emitted by a Single |
| from | Single | converts a Future into a Single |
| just | Single | returns a Single that emits a specified item |
| map | Single | returns a Single that emits the result of a function applied to the item emitted by the source Single |
| merge | Single | converts a Single that emits a second Single into a Single that emits the item emitted by the second Single |
| merge and mergeWith | Observable | merges the items emitted by multiple Singles as Observable emissions |
| observeOn | Single | instructs the Single to call the subscriber methods on a particular [Scheduler](scheduler) |
| onErrorReturn | Single | converts a Single that makes an error notification into a Single that emits a specified item |
| subscribeOn | Single | instructs the Single to operate on a particular [Scheduler](scheduler) |
| timeout | Single | returns a Single that makes an error notification if the source Single does not emit a value in a specified time period |
| toSingle | Single | converts an Observable that emits a single item into a Single that emits that item |
| toObservable | Observable | converts a Single into an Observable that emits the item emitted by the Single and then completes |
| zip and zipWith | Single | returns a Single that emits an item that is the result of a function applied to items emitted by two or more other Singles |

  The following sections of this page will give marble diagrams that explain these operators schematically. This diagram explains how Singles are represented in marble diagrams: 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.legend.png) 


compose
-------

 concat and concatWith
---------------------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concat.png)  There is also an instance version of this operator: 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatWith.png) create
------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.create.png) delay
-----

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delay.png)  There is also a version of this operator that allows you to perform the delay on a particular [Scheduler](scheduler): 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delay.s.png) doOnError
---------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnError.png) doOnSuccess
-----------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnSuccess.png) error
-----

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.error.png) flatMap
-------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.flatMap.png) flatMapObservable
-----------------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.flatMapObservable.png) from
----

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.from.Future.png) There is also a variety that takes a [Scheduler](scheduler) as an argument: ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.from.Future.s.png) 


just
----

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.just.png) map
---

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.map.png) merge and mergeWith
-------------------

  One version of merge takes a Single that emits a second Single and converts it into a Single that emits the item emitted by that second Single: 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.oo.png)  Another version takes two or more Singles and merges them into an Observable that emits the items emitted by the source Singles (in an arbitrary order): 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png) observeOn
---------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.observeOn.png) onErrorReturn
-------------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorReturn.png) subscribeOn
-----------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribeOn.png) timeout
-------

  Timeout will cause a Single to abort with an error notification if it does not emit an item in a specified period of time after it is subscribed to. One version allows you to set this time out by means of a number of specified time units: 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.1.png)  You can also specify a particular [Scheduler](scheduler) for the timer to operate on: 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.1s.png)  A version of the timeout operator allows you to switch to a backup Single rather than sending an error notification if the timeout expires: 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.2.png)  This, too, has a [Scheduler](scheduler)-specific version: 

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.2s.png) toObservable
------------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.toObservable.png) zip and zipWith
---------------

 ![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.zip.png)

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/single.html>

Subject
=======

  A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items. 


 Because a Subject subscribes to an Observable, it will trigger that Observable to begin emitting items (if that Observable is “cold” — that is, if it waits for a subscription before it begins to emit items). This can have the effect of making the resulting Subject a “hot” Observable variant of the original “cold” Observable. 

 #### See Also

 * [To Use or Not to Use Subject](http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx) from Dave Sexton’s blog
* [Introduction to Rx: Subject](http://www.introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html#Subject)
* [101 Rx Samples: ISubject<T> and ISubject<T1,T2>](http://rxwiki.wikidot.com/101samples#toc44)
* [Advanced RxJava: Subject](http://akarnokd.blogspot.hu/2015/06/subjects-part-1.html) by Dávid Karnok
* [Using Subjects](http://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/subjects.html) by Dennis Stoyanov

 Varieties of Subject
--------------------

  There are four varieties of `Subject` that are designed for particular use cases. Not all of these are available in all implementations, and some implementations use other naming conventions (for example, in RxScala, what is called a “PublishSubject” here is known simply as a “Subject”): 

 ### AsyncSubject

  ![](http://reactivex.io/documentation/operators/images/S.AsyncSubject.png)  An `AsyncSubject` emits the last value (and only the last value) emitted by the source Observable, and only after that source Observable completes. (If the source Observable does not emit any values, the `AsyncSubject` also completes without emitting any values.) 

   ![](http://reactivex.io/documentation/operators/images/S.AsyncSubject.e.png)  It will also emit this same final value to any subsequent observers. However, if the source Observable terminates with an error, the `AsyncSubject` will not emit any items, but will simply pass along the error notification from the source Observable. 

  #### See Also

 * [Introduction to Rx: AsyncSubject](http://www.introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html#AsyncSubject)

 ### BehaviorSubject

  ![](http://reactivex.io/documentation/operators/images/S.BehaviorSubject.png)  When an observer subscribes to a `BehaviorSubject`, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s). 

   ![](http://reactivex.io/documentation/operators/images/S.BehaviorSubject.e.png)  However, if the source Observable terminates with an error, the `BehaviorSubject` will not emit any items to subsequent observers, but will simply pass along the error notification from the source Observable. 

  #### See Also

 * [Introduction to Rx: BehaviorSubject](http://www.introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html#BehaviorSubject)

 ### PublishSubject

  ![](http://reactivex.io/documentation/operators/images/S.PublishSubject.png)  `PublishSubject` emits to an observer only those items that are emitted by the source Observable(s) subsequent to the time of the subscription. 


 Note that a `PublishSubject` may begin emitting items immediately upon creation (unless you have taken steps to prevent this), and so there is a risk that one or more items may be lost between the time the Subject is created and the observer subscribes to it. If you need to guarantee delivery of all items from the source Observable, you’ll need either to form that Observable with [`Create`](operators/create) so that you can manually reintroduce “cold” Observable behavior (checking to see that all observers have subscribed before beginning to emit items), or switch to using a `ReplaySubject` instead. 

   ![](http://reactivex.io/documentation/operators/images/S.PublishSubject.e.png)  If the source Observable terminates with an error, the `PublishSubject` will not emit any items to subsequent observers, but will simply pass along the error notification from the source Observable. 

  ### ReplaySubject

  ![](http://reactivex.io/documentation/operators/images/S.ReplaySubject.png)  `ReplaySubject` emits to any observer all of the items that were emitted by the source Observable(s), regardless of when the observer subscribes. 


 There are also versions of `ReplaySubject` that will throw away old items once the replay buffer threatens to grow beyond a certain size, or when a specified timespan has passed since the items were originally emitted. 


 If you use a `ReplaySubject` as an observer, take care not to call its `onNext` method (or its other `on` methods) from multiple threads, as this could lead to coincident (non-sequential) calls, which violates [the Observable contract](contract) and creates an ambiguity in the resulting Subject as to which item or notification should be replayed first. 

  #### See Also

 * [Introduction to Rx: ReplaySubject](http://www.introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html#ReplaySubject)

 Language-Specific Information
-----------------------------

    ###  RxGroovy

     If you have a `Subject` and you want to pass it along to some other agent without exposing its `Subscriber` interface, you can mask it by calling its `asObservable` method, which will return the Subject as a pure `Observable`. 

 #### See Also

 * Javadoc: [`AsyncSubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/AsyncSubject.html)
* Javadoc: [`BehaviorSubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/BehaviorSubject.html)
* Javadoc: [`PublishSubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/PublishSubject.html)
* Javadoc: [`ReplaySubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/ReplaySubject.html)

      ###  RxJava 1․x

     If you have a `Subject` and you want to pass it along to some other agent without exposing its `Subscriber` interface, you can mask it by calling its `asObservable` method, which will return the Subject as a pure `Observable`. 

 #### See Also

 * Javadoc: [`AsyncSubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/AsyncSubject.html)
* Javadoc: [`BehaviorSubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/BehaviorSubject.html)
* Javadoc: [`PublishSubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/PublishSubject.html)
* Javadoc: [`ReplaySubject`](http://reactivex.io/RxJava/javadoc/rx/subjects/ReplaySubject.html)

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/subject.html>

Do
==

 
> register an action to take upon a variety of Observable lifecycle events

  ![Do](http://reactivex.io/documentation/operators/images/do.c.png)  You can register callbacks that ReactiveX will call when certain events take place on an Observable, where those callbacks will be called independently from the normal set of notifications associated with an Observable cascade. There are a variety of operators that various ReactiveX implementations have designed to allow for this. 

  #### See Also

 * [Subscribe](subscribe)
* [Introduction to Rx: Do](http://www.introtorx.com/Content/v1.0.10621.0/09_SideEffects.html#Do)
* [Introduction to Rx: Finally](http://www.introtorx.com/Content/v1.0.10621.0/11_AdvancedErrorHandling.html#Finally)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `doOnCompleted doOnEach doOnError doOnNext doOnRequest doOnSubscribe doOnTerminate doOnUnsubscribe finallyDo`

     RxGroovy has several Do variants. 

  ![doOnEach](http://reactivex.io/documentation/operators/images/doOnEach.png)  The `doOnEach` operator allows you to establish a callback that the resulting Observable will call each time it emits an item. You can pass this callback either in the form of an `Action` that takes an `onNext` variety of `Notification` as its sole parameter, or you can pass in an Observer whose `onNext` method will be called as if it had subscribed to the Observable. 

 * Javadoc: [`doOnEach(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnEach(rx.functions.Action1))
* Javadoc: [`doOnEach(Observer)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnEach(rx.Observer))
   ![doOnNext](http://reactivex.io/documentation/operators/images/doOnNext.png)  The `doOnNext` operator is much like `doOnEach(Action1)` except that the `Action` that you pass it as a parameter does not accept a `Notification` but instead simply accepts the emitted item. 

 * Javadoc: [`doOnNext(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnNext(rx.functions.Action1))
    The `doOnRequest` operator (new in RxGroovy 1.1) registers an `Action` which will be called whenever an observer requests additional items from the resulting Observable. That `Action` receives as its parameter the number of items that the observer is requesting. 

 * Javadoc: [`doOnRequest(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnRequest(rx.functions.Action1))
   ![doOnSubscribe](http://reactivex.io/documentation/operators/images/doOnSubscribe.png)  The `doOnSubscribe` operator registers an `Action` which will be called whenever an observer subscribes to the resulting Observable. 

 * Javadoc: [`doOnSubscribe(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnSubscribe(rx.functions.Action0))
   ![doOnUnsubscribe](http://reactivex.io/documentation/operators/images/doOnUnsubscribe.png)  The `doOnUnsubscribe` operator registers an `Action` which will be called whenever an observer unsubscribes from the resulting Observable. 

 * Javadoc: [`doOnUnsubscribe(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnUnsubscribe(rx.functions.Action0))
   ![doOnCompleted](http://reactivex.io/documentation/operators/images/doOnCompleted.png)  The `doOnCompleted` operator registers an `Action` which will be called if the resulting Observable terminates normally, calling `onCompleted`. 

 * Javadoc: [`doOnCompleted(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnCompleted(rx.functions.Action0))
   ![doOnError](http://reactivex.io/documentation/operators/images/doOnError.png)  The `doOnError` operator registers an `Action` which will be called if the resulting Observable terminates abnormally, calling `onError`. This `Action` will be passed the `Throwable` representing the error. 

 * Javadoc: [`doOnError(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnError(rx.functions.Action1))
   ![doOnTerminate](http://reactivex.io/documentation/operators/images/doOnTerminate.png)  The `doOnTerminate` operator registers an `Action` which will be called just *before* the resulting Observable terminates, whether normally or with an error. 

 * Javadoc: [`doOnTerminate(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnTerminate(rx.functions.Action0))
   ![finallyDo](http://reactivex.io/documentation/operators/images/finallyDo.png)  The `finallyDo` operator registers an `Action` which will be called just *after* the resulting Observable terminates, whether normally or with an error. 

 #### Sample Code

 
```
def numbers = Observable.from([1, 2, 3, 4, 5]);

numbers.finallyDo({ println('Finally'); }).subscribe(
   { println(it); },                          // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
2
3
4
5
Sequence complete
Finally
```
 * Javadoc: [`finallyDo(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#finallyDo(rx.functions.Action0))
       ###  RxJava 1․x `doOnCompleted doOnEach doOnError doOnNext doOnRequest doOnSubscribe doOnTerminate doOnUnsubscribe finallyDo doAfterTerminate`

     RxJava has several Do variants. 

  ![doOnEach](http://reactivex.io/documentation/operators/images/doOnEach.png)  The `doOnEach` operator allows you to establish a callback that the resulting Observable will call each time it emits an item. You can pass this callback either in the form of an `Action` that takes an `onNext` variety of `Notification` as its sole parameter, or you can pass in an Observer whose `onNext` method will be called as if it had subscribed to the Observable. 

 * Javadoc: [`doOnEach(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnEach(rx.functions.Action1))
* Javadoc: [`doOnEach(Observer)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnEach(rx.Observer))
   ![doOnNext](http://reactivex.io/documentation/operators/images/doOnNext.png)  The `doOnNext` operator is much like `doOnEach(Action1)` except that the `Action` that you pass it as a parameter does not accept a `Notification` but instead simply accepts the emitted item. 

 #### Sample Code

 
```
Observable.just(1, 2, 3)
          .doOnNext(new Action1<Integer>() {
          @Override
          public void call(Integer item) {
            if( item > 1 ) {
              throw new RuntimeException( "Item exceeds maximum value" );
            }
          }
        }).subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Error: Item exceeds maximum value
```
 * Javadoc: [`doOnNext(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnNext(rx.functions.Action1))
    The `doOnRequest` operator (new in RxJava 1.1) registers an `Action` which will be called whenever an observer requests additional items from the resulting Observable. That `Action` receives as its parameter the number of items that the observer is requesting. 

 * Javadoc: [`doOnRequest(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnRequest(rx.functions.Action1))
   ![doOnSubscribe](http://reactivex.io/documentation/operators/images/doOnSubscribe.png)  The `doOnSubscribe` operator registers an `Action` which will be called whenever an observer subscribes to the resulting Observable. 

 * Javadoc: [`doOnSubscribe(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnSubscribe(rx.functions.Action0))
   ![doOnUnsubscribe](http://reactivex.io/documentation/operators/images/doOnUnsubscribe.png)  The `doOnUnsubscribe` operator registers an `Action` which will be called whenever an observer unsubscribes from the resulting Observable. 

 * Javadoc: [`doOnUnsubscribe(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnUnsubscribe(rx.functions.Action0))
   ![doOnCompleted](http://reactivex.io/documentation/operators/images/doOnCompleted.png)  The `doOnCompleted` operator registers an `Action` which will be called if the resulting Observable terminates normally, calling `onCompleted`. 

 * Javadoc: [`doOnCompleted(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnCompleted(rx.functions.Action0))
   ![doOnError](http://reactivex.io/documentation/operators/images/doOnError.png)  The `doOnError` operator registers an `Action` which will be called if the resulting Observable terminates abnormally, calling `onError`. This `Action` will be passed the `Throwable` representing the error. 

 * Javadoc: [`doOnError(Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnError(rx.functions.Action1))
   ![doOnTerminate](http://reactivex.io/documentation/operators/images/doOnTerminate.png)  The `doOnTerminate` operator registers an `Action` which will be called just *before* the resulting Observable terminates, whether normally or with an error. 

 * Javadoc: [`doOnTerminate(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doOnTerminate(rx.functions.Action0))
   ![finallyDo](http://reactivex.io/documentation/operators/images/finallyDo.png)  `finallyDo` is deprecated since RxJava 1.1.1, in favor of `doAfterTerminate` with the same behavior. 


 The `finallyDo` operator registers an `Action` which will be called just *after* the resulting Observable terminates, whether normally or with an error. 

 * Javadoc: [`finallyDo(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#finallyDo(rx.functions.Action0))
   ![doAfterTerminate](http://reactivex.io/documentation/operators/images/doAfterTerminate.png)  The `doAfterTerminate` operator registers an `Action` which will be called just *after* the resulting Observable terminates, whether normally or with an error. 

 * Javadoc: [`doAfterTerminate(Action0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#doAfterTerminate(rx.functions.Action0))
       ###  RxJS `do doOnCompleted doOnError doOnNext finally tap tapOnCompleted tapOnError tapOnNext`

     ![do](http://reactivex.io/documentation/operators/images/do.png)  RxJS implements the basic Do operator as `do` or `tap` (two names for the same operator). You have two choices for how to use this operator: 

 1. You can pass it an Observer, in which case `do`/`tap` will call that Observer’s methods as though that Observer had subscribed to the resulting Observable.
2. You can pass in a set of 1–3 individual functions (`onNext`, `onError`, and `onCompleted`) that `do`/`tap` will call along with the similarly-named functions of any of its observers.

 #### Sample Code

 
```
/* Using an observer */
var observer = Rx.Observer.create(
  function (x) { console.log('Do Next: %s', x); },
  function (err) { console.log('Do Error: %s', err); },
  function () { console.log('Do Completed'); }
);

var source = Rx.Observable.range(0, 3)
    .do(observer);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Do Next: 0
Next: 0
Do Next: 1
Next: 1
Do Next: 2
Next: 2
Do Completed
Completed
```
 
```
/* Using a function */
var source = Rx.Observable.range(0, 3)
  .do(
    function (x)   { console.log('Do Next:', x); },
    function (err) { console.log('Do Error:', err); },
    function ()    { console.log('Do Completed'); }
  );

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Do Next: 0
Next: 0
Do Next: 1
Next: 1
Do Next: 2
Next: 2
Do Completed
Completed
```
    ![doOnNext](http://reactivex.io/documentation/operators/images/doOnNext.png)  RxJS also implements `doOnNext` or `tapOnNext` (two names for the same operator). It is a specialized form of Do that responds only to the `onNext` case, by calling a callback function you provide as a parameter. You may also optionally pass a second parameter that will be the “`this`” object from the point of view of your callback function when it executes. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 3)
  .doOnNext(
    function () { this.log('Do Next: %s', x); },
    console
  );

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Do Next: 0
Next: 0
Do Next: 1
Next: 1
Do Next: 2
Next: 2
Completed
```
    ![doOnError](http://reactivex.io/documentation/operators/images/doOnError.png)  RxJS also implements `doOnError` or `tapOnError` (two names for the same operator). It is a specialized form of Do that responds only to the `onError` case, by calling a callback function you provide as a parameter. You may also optionally pass a second parameter that will be the “`this`” object from the point of view of your callback function when it executes. 

 #### Sample Code

 
```
var source = Rx.Observable.throw(new Error());
  .doOnError(
    function (err) { this.log('Do Error: %s', err); },
    console
  );

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Do Error: Error
Error: Error
```
    ![doOnCompleted](http://reactivex.io/documentation/operators/images/doOnCompleted.png)  RxJS also implements `doOnCompleted` or `tapOnCompleted` (two names for the same operator). It is a specialized form of Do that responds only to the `onCompleted` case, by calling a callback function you provide as a parameter. You may also optionally pass a second parameter that will be the “`this`” object from the point of view of your callback function when it executes. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 3)
  .doOnCompleted(
    function () { this.log('Do Completed'); },
    console
  );

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Do Completed
Completed
```
    ![finally](http://reactivex.io/documentation/operators/images/finally.png)  RxJS also implements a `finally` operator. It takes a function that will be called after the resulting Observable terminates, whether normally (`onCompleted`) or abnormally (`onError`). 

 #### Sample Code

 
```
var source = Rx.Observable.throw(new Error())
    .finally(function () {
        console.log('Finally');
    });

var subscription = source.subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
```
 
```
Error: Error
Finally
```
    `do`/`tap`, `doOnNext`/`tapOnNext`, `doOnError`/`tapOnError`, `doOnCompleted`/`tapOnCompleted`, and `finally` are found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `do doOnError doOnCompleted finally`

       RxPHP implements this operator as `do`. 

  Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. When using do, it is important to note that the Observer may receive additional events after a stream has completed or errored (such as when using a repeat or resubscribing). If you are using an Observable that extends the AbstractObservable, you will not receive these events. For this special case, use the DoObserver. doOnNext, doOnError, and doOnCompleted uses the DoObserver internally and will receive these additional events. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/do/do.php

$source = \Rx\Observable::range(0, 3)
    ->do(
        function ($x) {
            echo 'Do Next:', $x, PHP_EOL;
        },
        function (Throwable $err) {
            echo 'Do Error:', $err->getMessage(), PHP_EOL;
        },
        function () {
            echo 'Do Completed', PHP_EOL;
        }
    );

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Do Next:0
Next value: 0
Do Next:1
Next value: 1
Do Next:2
Next value: 2
Do Completed
Complete!
```
      RxPHP also has an operator `doOnError`. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/do/doOnError.php

$source = \Rx\Observable::error(new Exception('Oops'))
    ->doOnError(function (Throwable $err) {
        echo 'Do Error:', $err->getMessage(), PHP_EOL;
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Do Error:Oops
Exception: Oops
```
      RxPHP also has an operator `doOnCompleted`. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/do/doOnCompleted.php

$source = \Rx\Observable::empty()
    ->doOnCompleted(function () {
        echo 'Do Completed', PHP_EOL;
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Do Completed
Complete!
```
      RxPHP also has an operator `finally`. 

  Will call a specified function when the source terminates on complete or error. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/finally/finally.php

Rx\Observable::range(1, 3)
    ->finally(function() {
        echo "Finally\n";
    })
    ->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Next value: 3
Complete!
Finally
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/finally/finally-error.php

Rx\Observable::range(1, 3)
    ->map(function($value) {
        if ($value == 2) {
            throw new \Exception('error');
        }
        return $value;
    })
    ->finally(function() {
        echo "Finally\n";
    })
    ->subscribe($stdoutObserver);
```
  
```
Next value: 1
Exception: error
Finally
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/do.html>

Scheduler
=========

  If you want to introduce multithreading into your cascade of Observable operators, you can do so by instructing those operators (or particular Observables) to operate on particular Schedulers. 


 Some ReactiveX Observable operators have variants that take a Scheduler as a parameter. These instruct the operator to do some or all of its work on a particular Scheduler. 

   By default, an Observable and the chain of operators that you apply to it will do its work, and will notify its observers, on the same thread on which its `Subscribe` method is called. The SubscribeOn operator changes this behavior by specifying a different Scheduler on which the Observable should operate. The ObserveOn operator specifies a different Scheduler that the Observable will use to send notifications to its observers. 


 As shown in this illustration, the SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called. ObserveOn, on the other hand, affects the thread that the Observable will use *below* where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate. 

 ![ObserveOn and SubscribeOn](http://reactivex.io/documentation/operators/images/schedulers.png)  #### See Also

 * [Introduction to Rx: Scheduling and Threading](http://www.introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html)
* [Rx Workshop: Schedulers](http://channel9.msdn.com/Series/Rx-Workshop/Rx-Workshop-Schedulers)
* [Using Schedulers](http://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/scheduling_and_concurrency.html) by Dennis Stoyanov

 Language-Specific Information
-----------------------------

    ###  RxGroovy

    Varieties of Scheduler
----------------------

  You obtain a Scheduler from the factory methods described in [the `Schedulers` class](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html). The following table shows the varieties of Scheduler that are available to you by means of these methods in RxGroovy: 

 

| Scheduler | purpose |
| --- | --- |
| [`Schedulers.computation( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#computation()) | meant for computational work such as event-loops and callback processing; do not use this scheduler for I/O (use `Schedulers.io( )` instead); the number of threads, by default, is equal to the number of processors |
| [`Schedulers.from(executor)`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#from(java.util.concurrent.Executor)) | uses the specified `Executor` as a Scheduler |
| [`Schedulers.immediate( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#immediate()) | schedules work to begin immediately in the current thread |
| [`Schedulers.io( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#io()) | meant for I/O-bound work such as asynchronous performance of blocking I/O, this scheduler is backed by a thread-pool that will grow as needed; for ordinary computational work, switch to `Schedulers.computation( )`; `Schedulers.io( )` by default is a `CachedThreadScheduler`, which is something like a new thread scheduler with thread caching |
| [`Schedulers.newThread( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#newThread()) | creates a new thread for each unit of work |
| [`Schedulers.trampoline( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#trampoline()) | queues work to begin on the current thread after any already-queued work |

 Default Schedulers for RxGroovy Observable Operators
----------------------------------------------------

  Some Observable operators in RxGroovy have alternate forms that allow you to set which Scheduler the operator will use for (at least some part of) its operation. Others do not operate on any particular Scheduler, or operate on a particular default Scheduler. Those that have a particular default Scheduler include: 

 

| operator | Scheduler |
| --- | --- |
| [`buffer(timespan)`](operators/buffer) | `computation` |
| [`buffer(timespan, count)`](operators/buffer) | `computation` |
| [`buffer(timespan, timeshift)`](operators/buffer) | `computation` |
| [`debounce(timeout, unit)`](operators/debounce) | `computation` |
| [`delay(delay, unit)`](operators/delay) | `computation` |
| [`delaySubscription(delay, unit)`](operators/delay) | `computation` |
| [`interval`](operators/interval) | `computation` |
| [`repeat`](operators/repeat) | `trampoline` |
| [`replay(time, unit)`](operators/replay) | `computation` |
| [`replay(buffersize, time, unit)`](operators/replay) | `computation` |
| [`replay(selector, time, unit)`](operators/replay) | `computation` |
| [`replay(selector, buffersize, time, unit)`](operators/replay) | `computation` |
| [`retry`](operators/retry) | `trampoline` |
| [`sample(period, unit)`](operators/sample) | `computation` |
| [`skip(time, unit)`](operators/skip) | `computation` |
| [`skipLast(time, unit)`](operators/skiplast) | `computation` |
| [`take(time, unit)`](operators/take) | `computation` |
| [`takeLast(time, unit)`](operators/takelast) | `computation` |
| [`takeLast(count, time, unit)`](operators/takelast) | `computation` |
| [`takeLastBuffer(time, unit)`](operators/takelast) | `computation` |
| [`takeLastBuffer(count, time, unit)`](operators/takelast) | `computation` |
| [`throttleFirst`](operators/sample) | `computation` |
| [`throttleLast`](operators/sample) | `computation` |
| [`throttleWithTimeout`](operators/debounce) | `computation` |
| [`timeInterval`](operators/timeinterval) | `immediate` |
| [`timeout(timeoutSelector)`](operators/timeout) | `immediate` |
| [`timeout(firstTimeoutSelector, timeoutSelector)`](operators/timeout) | `immediate` |
| [`timeout(timeoutSelector, other)`](operators/timeout) | `immediate` |
| [`timeout(timeout, timeUnit)`](operators/timeout) | `computation` |
| [`timeout(firstTimeoutSelector, timeoutSelector, other)`](operators/timeout) | `immediate` |
| [`timeout(timeout, timeUnit, other)`](operators/timeout) | `computation` |
| [`timer`](operators/timer) | `computation` |
| [`timestamp`](operators/timestamp) | `immediate` |
| [`window(timespan)`](operators/window) | `computation` |
| [`window(timespan, count)`](operators/window) | `computation` |
| [`window(timespan, timeshift)`](operators/window) | `computation` |

 Test Scheduler
--------------

  [The `TestScheduler`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html) allows you to exercise fine-tuned manual control over how the Scheduler’s clock behaves. This can be useful for testing interactions that depend on precise arrangements of actions in time. This Scheduler has three additional methods: 

  [`advanceTimeTo(time,unit)`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html#advanceTimeTo(long,%20java.util.concurrent.TimeUnit)) advances the Scheduler’s clock to a particular point in time [`advanceTimeBy(time,unit)`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html#advanceTimeBy(long,%20java.util.concurrent.TimeUnit)) advances the Scheduler’s clock forward by a particular amount of time [`triggerActions( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html#triggerActions()) start any unstarted actions that have been scheduled for a time equal to or earlier than the present time according to the Scheduler’s clock  #### See Also

 * [Testing Reactive Applications](https://speakerdeck.com/benjchristensen/applying-rxjava-to-existing-applications-at-philly-ete-2015) by Ben Christensen
* [RxJava Threading Examples](http://www.grahamlea.com/2014/07/rxjava-threading-examples/) by Graham Lea
* Advanced RxJava: Schedulers ([part 1](http://akarnokd.blogspot.hu/2015/05/schedulers-part-1.html)) ([part 2](http://akarnokd.blogspot.hu/2015/06/schedulers-part-2.html)) ([part 3](http://akarnokd.blogspot.hu/2015/06/schedulers-part-3.html)) ([part 4](http://akarnokd.blogspot.hu/2015/06/schedulers-part-4-final.html)) by Dávid Karnok

      ###  RxJava 1․x

    Varieties of Scheduler
----------------------

  You obtain a Scheduler from the factory methods described in [the `Schedulers` class](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html). The following table shows the varieties of Scheduler that are available to you by means of these methods in RxJava: 

 

| Scheduler | purpose |
| --- | --- |
| [`Schedulers.computation( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#computation()) | meant for computational work such as event-loops and callback processing; do not use this scheduler for I/O (use `Schedulers.io( )` instead); the number of threads, by default, is equal to the number of processors |
| [`Schedulers.from(executor)`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#from(java.util.concurrent.Executor)) | uses the specified `Executor` as a Scheduler |
| [`Schedulers.immediate( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#immediate()) | schedules work to begin immediately in the current thread |
| [`Schedulers.io( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#io()) | meant for I/O-bound work such as asynchronous performance of blocking I/O, this scheduler is backed by a thread-pool that will grow as needed; for ordinary computational work, switch to `Schedulers.computation( )`; `Schedulers.io( )` by default is a `CachedThreadScheduler`, which is something like a new thread scheduler with thread caching |
| [`Schedulers.newThread( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#newThread()) | creates a new thread for each unit of work |
| [`Schedulers.trampoline( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html#trampoline()) | queues work to begin on the current thread after any already-queued work |

 Default Schedulers for RxJava 1.x Observable Operators
------------------------------------------------------

  Some Observable operators in RxJava have alternate forms that allow you to set which Scheduler the operator will use for (at least some part of) its operation. Others do not operate on any particular Scheduler, or operate on a particular default Scheduler. Those that have a particular default Scheduler include: 

 

| operator | Scheduler |
| --- | --- |
| [`buffer(timespan)`](operators/buffer) | `computation` |
| [`buffer(timespan, count)`](operators/buffer) | `computation` |
| [`buffer(timespan, timeshift)`](operators/buffer) | `computation` |
| [`debounce(timeout, unit)`](operators/debounce) | `computation` |
| [`delay(delay, unit)`](operators/delay) | `computation` |
| [`delaySubscription(delay, unit)`](operators/delay) | `computation` |
| [`interval`](operators/interval) | `computation` |
| [`repeat`](operators/repeat) | `trampoline` |
| [`replay(time, unit)`](operators/replay) | `computation` |
| [`replay(buffersize, time, unit)`](operators/replay) | `computation` |
| [`replay(selector, time, unit)`](operators/replay) | `computation` |
| [`replay(selector, buffersize, time, unit)`](operators/replay) | `computation` |
| [`retry`](operators/retry) | `trampoline` |
| [`sample(period, unit)`](operators/sample) | `computation` |
| [`skip(time, unit)`](operators/skip) | `computation` |
| [`skipLast(time, unit)`](operators/skiplast) | `computation` |
| [`take(time, unit)`](operators/take) | `computation` |
| [`takeLast(time, unit)`](operators/takelast) | `computation` |
| [`takeLast(count, time, unit)`](operators/takelast) | `computation` |
| [`takeLastBuffer(time, unit)`](operators/takelast) | `computation` |
| [`takeLastBuffer(count, time, unit)`](operators/takelast) | `computation` |
| [`throttleFirst`](operators/sample) | `computation` |
| [`throttleLast`](operators/sample) | `computation` |
| [`throttleWithTimeout`](operators/debounce) | `computation` |
| [`timeInterval`](operators/timeinterval) | `immediate` |
| [`timeout(timeoutSelector)`](operators/timeout) | `immediate` |
| [`timeout(firstTimeoutSelector, timeoutSelector)`](operators/timeout) | `immediate` |
| [`timeout(timeoutSelector, other)`](operators/timeout) | `immediate` |
| [`timeout(timeout, timeUnit)`](operators/timeout) | `computation` |
| [`timeout(firstTimeoutSelector, timeoutSelector, other)`](operators/timeout) | `immediate` |
| [`timeout(timeout, timeUnit, other)`](operators/timeout) | `computation` |
| [`timer`](operators/timer) | `computation` |
| [`timestamp`](operators/timestamp) | `immediate` |
| [`window(timespan)`](operators/window) | `computation` |
| [`window(timespan, count)`](operators/window) | `computation` |
| [`window(timespan, timeshift)`](operators/window) | `computation` |

 Using Schedulers
----------------

  Aside from passing these Schedulers in to RxJava Observable operators, you can also use them to schedule your own work on Subscriptions. The following example uses [the `schedule` method](http://reactivex.io/RxJava/javadoc/rx/Scheduler.Worker.html#schedule(rx.functions.Action0)) of [the `Scheduler.Worker` class](http://reactivex.io/RxJava/javadoc/rx/Scheduler.Worker.html) to schedule work on the `newThread` Scheduler: 



```
worker = Schedulers.newThread().createWorker();
worker.schedule(new Action0() {

    @Override
    public void call() {
        yourWork();
    }

});
// some time later...
worker.unsubscribe();
```
 ### Recursive Schedulers

  To schedule recursive calls, you can use `schedule` and then `schedule(this)` on the Worker object: 

 
```
worker = Schedulers.newThread().createWorker();
worker.schedule(new Action0() {

    @Override
    public void call() {
        yourWork();
        // recurse until unsubscribed (schedule will do nothing if unsubscribed)
        worker.schedule(this);
    }

});
// some time later...
worker.unsubscribe();
```
 ### Checking or Setting Unsubscribed Status

  Objects of the `Worker` class implement [the `Subscription` interface](http://reactivex.io/RxJava/javadoc/rx/Subscription.html), with its [`isUnsubscribed`](http://reactivex.io/RxJava/javadoc/rx/Subscription.html#isUnsubscribed()) and [`unsubscribe`](http://reactivex.io/RxJava/javadoc/rx/Subscription.html#unsubscribe()) methods, so you can stop work when a subscription is cancelled, or you can cancel the subscription from within the scheduled task: 



```
Worker worker = Schedulers.newThread().createWorker();
Subscription mySubscription = worker.schedule(new Action0() {

    @Override
    public void call() {
        while(!worker.isUnsubscribed()) {
            status = yourWork();
            if(QUIT == status) { worker.unsubscribe(); }
        }
    }

});
```
  The `Worker` is also a `Subscription` and so you can (and should, eventually) call its `unsubscribe` method to signal that it can halt work and release resources: 

 
```
worker.unsubscribe();
```
 ### Delayed and Periodic Schedulers

  You can also use [a version of `schedule`](http://reactivex.io/RxJava/javadoc/rx/Scheduler.Worker.html#schedule(rx.functions.Action0,%20long,%20java.util.concurrent.TimeUnit)) that delays your action on the given Scheduler until a certain timespan has passed. The following example schedules `someAction` to be performed on `someScheduler` after 500ms have passed according to that Scheduler’s clock: 

 
```
someScheduler.schedule(someAction, 500, TimeUnit.MILLISECONDS);
```
  [Another `Scheduler` method](http://reactivex.io/RxJava/javadoc/rx/Scheduler.Worker.html#schedulePeriodically(rx.functions.Action0,%20long,%20long,%20java.util.concurrent.TimeUnit)) allows you to schedule an action to take place at regular intervals. The following example schedules `someAction` to be performed on `someScheduler` after 500ms have passed, and then every 250ms thereafter: 

 
```
someScheduler.schedulePeriodically(someAction, 500, 250, TimeUnit.MILLISECONDS);
```
 Test Scheduler
--------------

  [The `TestScheduler`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html) allows you to exercise fine-tuned manual control over how the Scheduler’s clock behaves. This can be useful for testing interactions that depend on precise arrangements of actions in time. This Scheduler has three additional methods: 

  [`advanceTimeTo(time,unit)`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html#advanceTimeTo(long,%20java.util.concurrent.TimeUnit)) advances the Scheduler’s clock to a particular point in time [`advanceTimeBy(time,unit)`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html#advanceTimeBy(long,%20java.util.concurrent.TimeUnit)) advances the Scheduler’s clock forward by a particular amount of time [`triggerActions( )`](http://reactivex.io/RxJava/javadoc/rx/schedulers/TestScheduler.html#triggerActions()) start any unstarted actions that have been scheduled for a time equal to or earlier than the present time according to the Scheduler’s clock  #### See Also

 * [RxJava Threading Examples](http://www.grahamlea.com/2014/07/rxjava-threading-examples/) by Graham Lea
* [Testing Reactive Applications](https://speakerdeck.com/benjchristensen/applying-rxjava-to-existing-applications-at-philly-ete-2015) by Ben Christensen
* Advanced RxJava: Schedulers ([part 1](http://akarnokd.blogspot.hu/2015/05/schedulers-part-1.html)) ([part 2](http://akarnokd.blogspot.hu/2015/06/schedulers-part-2.html)) ([part 3](http://akarnokd.blogspot.hu/2015/06/schedulers-part-3.html)) ([part 4](http://akarnokd.blogspot.hu/2015/06/schedulers-part-4-final.html)) by Dávid Karnok

      ###  RxJS

     In RxJS you obtain Schedulers from the `Rx.Scheduler` object or as independently-implemented objects. The following table shows the varieties of Scheduler that are available to you in RxJS:. 

 

| Scheduler | purpose |
| --- | --- |
| `Rx.Scheduler.currentThread` | schedules work as soon as possible on the current thread |
| `Rx.HistoricalScheduler` | schedules work as though it were occurring at an arbitrary historical time |
| `Rx.Scheduler.immediate` | schedules work immediately on the current thread |
| `Rx.TestScheduler` | for unit testing; this allows you to manually manipulate the movement of time |
| `Rx.Scheduler.timeout` | schedules work by means of a timed callback |

 #### See Also

 * [StackOverflow: What is a “Scheduler” in RxJS](http://stackoverflow.com/questions/28145890/what-is-a-scheduler-in-rxjs)
* [Schedulers](http://xgrommx.github.io/rx-book/content/schedulers/index.html) by Dennis Stoyanov
* [RxJava Threading Examlpes](http://www.grahamlea.com/2014/07/rxjava-threading-examples/) by Graham Lea

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/scheduler.html>

The Observable Contract
=======================

  “The Observable Contract,” which you may see referenced in various places in source documentation and in the pages on this site, is an attempt at a formal definition of an Observable, based originally on the 2010 document [Rx Design Guidelines](https://go.microsoft.com/fwlink/?LinkID=205219) from Microsoft that described its Rx.NET implementation of ReactiveX. 


 This page summarizes The Observable Contract. 

 Notifications
-------------

  An Observable communicates with its observers with the following *notifications*: 

  OnNext conveys an *item* that is *emitted* by the Observable to the observer OnCompleted indicates that the Observable has completed successfully and that it will be emitting no further items OnError indicates that the Observable has terminated with a specified error condition and that it will be emitting no further items OnSubscribe (optional) indicates that the Observable is ready to accept Request notifications from the observer (see *Backpressure* below)   An observer communicates with its Observable by means of the following notifications: 

  Subscribe indicates that the observer is ready to receive notifications from the Observable Unsubscribe indicates that the observer no longer wants to receive notifications from the Observable Request (optional) indicates that the observer wants no more than a particular number of additional OnNext notifications from the Observable (see *Backpressure* below)  The Contract Governing Notifications
------------------------------------

  An Observable may make zero or more OnNext notifications, each representing a single emitted item, and it may then follow those emission notifications by either an OnCompleted or an OnError notification, but not both. Upon issuing an OnCompleted or OnError notification, it may not thereafter issue any further notifications. 


 An Observable may emit no items at all. An Observable may also never terminate with either an OnCompleted or an OnError notification. That is to say that it is proper for an Observable to issue no notifications, to issue only an OnCompleted or an OnError notification, or to issue only OnNext notifications. 


 Observables must issue notifications to observers serially (not in parallel). They may issue these notifications from different threads, but there must be a formal *happens-before* relationship between the notifications. 

 Observable Termination
----------------------

  If an Observable has not issued an OnCompleted or OnError notification, an observer may consider it to be still active (even if it is not currently emitting items) and may issue it notifications (such as an Unsubscribe or Request notification). When an Observable does issue an OnCompleted or OnError notification, the Observable may release its resources and terminate, and its observers should not attempt to communicate with it any further. 


 An OnError notification must contain the cause of the error (that is to say, it is invalid to call OnError with a `null` value). 


 Before an Observable terminates it must first issue either an OnCompleted or OnError notification to all of the observers that are subscribed to it. 

 Subscribing and Unsubscribing
-----------------------------

  An Observable may begin issuing notifications to an observer immediately after the Observable receives a Subscribe notification from the observer. 


 When an observer issues an Unsubscribe notification to an Observable, the Observable will attempt to stop issuing notifications to the observer. It is not guaranteed, however, that the Observable will issue *no* notifications to the observer after an observer issues it an Unsubscribe notification. 


 When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end subscriptions that are ended by the Observable in this way. 

 Multiple Observers
------------------

  If a second observer subscribes to an Observable that is already emitting items to a first observer, it is up to the Observable whether it will thenceforth emit the same items to each observer, or whether it will replay the complete sequence of items from the beginning to the second observer, or whether it will emit a wholly different sequence of items to the second observer. There is no general guarantee that two observers of the same Observable will see the same sequence of items. 

 Backpressure
------------

  Backpressure is optional; not all ReactiveX implementations include backpressure, and in those that do, not all Observables or operators honor backpressure. An Observable *may* implement backpressure if it detects that its observer implements *Request* notifications and understands *OnSubscribe* notifications. 


 If an Observable implements backpressure and its observer employs backpressure, the Observable will not begin to emit items to the observer immediately upon subscription. Instead, it will issue an OnSubscribe notification to the observer. 


 At any time after it receives an OnSubscribe notification, an observer may issue a Request notification to the Observable it has subscribed to. This notification requests a particular number of items. The Observable responds to such a Request by emitting no more items to the observer than the number of items the observer requests. However the Observable may, in addition, issue an OnCompleted or OnError notification, and it may even issue such a notification before the observer requests any items at all. 


 An Observable that does not implement backpressure should respond to a Request notification from an observer by issuing an OnError notification that indicates that backpressure is not supported. 


 Requests are cumulative. For example, if an observer issues three Request notifications to an Observable, for 3, 5, and 10 items respectively, that Observable may emit as many as 18 items to the observer, no matter when those Request notifications arrived relative to when the Observable emitted items in response. 


 If the Observable produces more items than the observer requests, it is up to the Observable whether it will discard the excess items, store them to emit at a later time, or use some other strategy to deal with the overflow. 

 See Also
--------

 * [Rx Design Guidelines](https://go.microsoft.com/fwlink/?LinkID=205219)
* [RxJS Design Guidelines](http://xgrommx.github.io/rx-book/content/guidelines/index.html)



 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/contract.html>

Connect
=======

 
> instruct a connectable Observable to begin emitting items to its subscribers

  ![Connect](http://reactivex.io/documentation/operators/images/publishConnect.c.png)  A connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when the Connect operator is applied to it. In this way you can wait for all intended observers to subscribe to the Observable before the Observable begins emitting items. 

  #### See Also

 * [Publish](publish)
* [RefCount](refcount)
* [Replay](replay)
* [Introduction to Rx: Publish & Connect](http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#PublishAndConnect)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `connect`

     ![connect](http://reactivex.io/documentation/operators/images/publishConnect.png)  In RxGroovy, the `connect` operator is a method of the `ConnectableObservable` interface. You can use the `publish` operator to convert an ordinary Observable into a `ConnectableObservable`. 


 Call a `ConnectableObservable`’s `connect` method to instruct it to begin emitting the items from its underlying Observable to its Subscribers. 


 The `connect` method returns a `Subscription`. You can call that `Subscription` object’s `unsubscribe` method to instruct the Observable to stop emitting items to its Subscribers. 


 You can also use the `connect` method to instruct an Observable to begin emitting items (or, to begin generating items that would be emitted) even before any Subscriber has subscribed to it. In this way you can turn a cold Observable into a hot one. 

 * Javadoc: [`connect()`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html#connect())
* Javadoc: [`connect(Action1)`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html#connect(rx.functions.Action1))
       ###  RxJava 1․x `connect`

     ![connect](http://reactivex.io/documentation/operators/images/publishConnect.png)  In RxJava, the `connect` operator is a method of the `ConnectableObservable` interface. You can use the `publish` operator to convert an ordinary Observable into a `ConnectableObservable`. 


 Call a `ConnectableObservable`’s `connect` method to instruct it to begin emitting the items from its underlying Observable to its Subscribers. 


 The `connect` method returns a `Subscription`. You can call that `Subscription` object’s `unsubscribe` method to instruct the Observable to stop emitting items to its Subscribers. 


 You can also use the `connect` method to instruct an Observable to begin emitting items (or, to begin generating items that would be emitted) even before any Subscriber has subscribed to it. In this way you can turn a cold Observable into a hot one. 

 * Javadoc: [`connect()`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html#connect())
* Javadoc: [`connect(Action1)`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html#connect(rx.functions.Action1))
       ###  RxJS `connect`

     ![connect](http://reactivex.io/documentation/operators/images/publishConnect.png)  In RxJS, the `connect` operator is a method of the `ConnectableObservable` prototype. You can use the `publish` operator to convert an ordinary Observable into a `ConnectableObservable`. 


 Call a `ConnectableObservable`’s `connect` method to instruct it to begin emitting the items from its underlying Observable to its Subscribers. 


 The `connect` method returns a `Disposable`. You can call that `Disposable` object’s `dispose` method to instruct the Observable to stop emitting items to its Subscribers. 


 You can also use the `connect` method to instruct an Observable to begin emitting items (or, to begin generating items that would be emitted) even before any Subscriber has subscribed to it. In this way you can turn a cold Observable into a hot one. 

 #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(2)
    .do(function (x) { console.log('Side effect'); });

var published = source.publish();

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

// Connect the source
var connection = published.connect();

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Side effect
Next: SourceA0
Next: SourceB0
Side effect
Next: SourceA1
Next: SourceB1
Completed
Completed
```
  `connect` is found in the following packages: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.all.binding.js`

  `connect` requires one of the following packages: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/connect.html>

Backpressure Operators
======================

 
> strategies for coping with Observables that produce items more rapidly than their observers consume them

  In ReactiveX it is not difficult to get into a situation in which an Observable is emitting items more rapidly than an operator or observer can consume them. This presents the problem of what to do with such a growing backlog of unconsumed items. 


 For example, imagine using the [Zip](zip) operator to zip together two infinite Observables, one of which emits items twice as frequently as the other. A naive implementation of the operator would have to maintain an ever-expanding buffer of items emitted by the faster Observable to eventually combine with items emitted by the slower one. This could cause ReactiveX to seize an unwieldy amount of system resources. 


 There are a variety of strategies with which you can exercise flow control and backpressure in ReactiveX in order to alleviate the problems caused when a quickly-producing Observable meets a slow-consuming observer, which include, in some ReactiveX implementations, reactive pull backpressure and some backpressure-specific operators. 


 A cold Observable emits a particular sequence of items, but can begin emitting this sequence when its observer finds it to be convenient, and at whatever rate the observer desires, without disrupting the integrity of the sequence. For example if you convert a static iterable into an Observable, that Observable will emit the same sequence of items no matter when it is later subscribed to or how frequently those items are observed. Examples of items emitted by a cold Observable might include the results of a database query, file retrieval, or web request. 


 A hot Observable begins generating items to emit immediately when it is created. Subscribers typically begin observing the sequence of items emitted by a hot Observable from somewhere in the middle of the sequence, beginning with the first item emitted by the Observable subsequent to the establishment of the subscription. Such an Observable emits items at its own pace, and it is up to its observers to keep up. Examples of items emitted by a hot Observable might include mouse & keyboard events, system events, or stock prices. 


 When a cold Observable is multicast (when it is converted into a connectable Observable and its [Connect](connect) method is called), it effectively becomes hot and for the purposes of backpressure and flow-control it should be treated as a hot Observable. 


 Cold Observables are ideal for the reactive pull model of backpressure implemented by some implementations of ReactiveX (which is described elsewhere). Hot Observables typically do not cope well with a reactive pull model, and are better candidates for other flow control strategies, such as the use of the operators described on this page, or operators like [Buffer](buffer), [Sample](sample), [Debounce](debounce), or [Window](window). 

 #### See Also

 * [Buffer](buffer)
* [Sample](sample)
* [Debounce](debounce)
* [Window](window)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `onBackpressureBuffer onBackpressureDrop onBackpressureLatest`

     RxGroovy implements reactive pull backpressure, and many of its operators support that form of backpressure. It also has three operators that you can apply to Observables that have not been written to support backpressure:  ![onBackpressureBuffer](http://reactivex.io/documentation/operators/images/bp.obp.buffer.png)  `onBackpressureBuffer` maintains a buffer of all unobserved emissions from the source Observable and emits them to downstream observers according to the requests they generate. 


 A version of this operator that was introduced in RxGroovy 1.1 allows you to set the capacity of the buffer; applying this operator will cause the resulting Observable to terminate with an error if this buffer is overrun. A second version, introduced during the same release, allows you to set an `Action` that `onBackpressureBuffer` will call if the buffer is overrun. 


* Javadoc: [`onBackpressureBuffer()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureBuffer())
* Javadoc: [`onBackpressureBuffer(long)` (RxGroovy 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureBuffer(long))
* Javadoc: [`onBackpressureBuffer(long, Action0)` (RxGroovy 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureBuffer(long,%20rx.functions.Action0))
   ![onBackpressureDrop](http://reactivex.io/documentation/operators/images/bp.obp.drop.png)  `onBackpressureDrop` drops emissions from the source Observable unless there is a pending request from a downstream observer, in which case it will emit enough items to fulfill the request. 


 A version of this operator that was introduced in the 1.1 release notifies you, by means of an `Action` you pass as a parameter, when an item has been dropped and which item was dropped. 


* Javadoc: [`onBackpressureDrop()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureDrop())
* Javadoc: [onBackpressureDrop(Action1) (RxGroovy 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureDrop(rx.functions.Action1))
   ![onBackpressureLatest](http://reactivex.io/documentation/operators/images/bp.obp.latest.png)  `onBackpressureLatest` (new in RxJava 1.1) holds on to the most-recently emitted item from the source Observable and immediately emits that item to its observer upon request. It drops any other items that it observes between requests from its observer. 


* Javadoc: [`onBackpressureLatest()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureLatest())
  


     ###  RxJava 1․x `onBackpressureBuffer onBackpressureDrop onBackpressureLatest`

     RxJava implements reactive pull backpressure, and many of its operators support that form of backpressure. It also has three operators that you can apply to Observables that have not been written to support backpressure:  ![onBackpressureBuffer](http://reactivex.io/documentation/operators/images/bp.obp.buffer.png)  `onBackpressureBuffer` maintains a buffer of all unobserved emissions from the source Observable and emits them to downstream observers according to the requests they generate. 


 A version of this operator that was introduced in RxJava 1.1 allows you to set the capacity of the buffer; applying this operator will cause the resulting Observable to terminate with an error if this buffer is overrun. A second version, introduced during the same release, allows you to set an `Action` that `onBackpressureBuffer` will call if the buffer is overrun. 


* Javadoc: [`onBackpressureBuffer()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureBuffer())
* Javadoc: [`onBackpressureBuffer(long)` (RxJava 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureBuffer(long))
* Javadoc: [`onBackpressureBuffer(long, Action0)` (RxJava 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureBuffer(long,%20rx.functions.Action0))
   ![onBackpressureDrop](http://reactivex.io/documentation/operators/images/bp.obp.drop.png)  `onBackpressureDrop` drops emissions from the source Observable unless there is a pending request from a downstream observer, in which case it will emit enough items to fulfill the request. 


 A version of this operator that was introduced in the 1.1 release notifies you, by means of an `Action` you pass as a parameter, when an item has been dropped and which item was dropped. 


* Javadoc: [`onBackpressureDrop()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureDrop())
* Javadoc: [onBackpressureDrop(Action1) (RxJava 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureDrop(rx.functions.Action1))
   ![onBackpressureLatest](http://reactivex.io/documentation/operators/images/bp.obp.latest.png)  `onBackpressureLatest` (new in RxJava 1.1) holds on to the most-recently emitted item from the source Observable and immediately emits that item to its observer upon request. It drops any other items that it observes between requests from its observer. 


* Javadoc: [`onBackpressureLatest()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onBackpressureLatest())
  


     ###  RxJS `controlled pausable pausableBuffered stopAndWait windowed`

     RxJS implements backpressure by transforming an ordinary Observable into a `ControlledObservable` with the `controlled` operator. This forces the Observable to respect pull `request`s from its observer rather than pushing items on its own initiative. 

  ![stopAndWait](http://reactivex.io/documentation/operators/images/bp.stopAndWait.png)  As an alternative to using `request` to pull items from a `ControlledObservable`, you may apply the `stopAndWait` operator to it. This operator will request a new item from the Observable each time its observers’ `onNext` routine receives the latest item. 

   ![windowed](http://reactivex.io/documentation/operators/images/bp.windowed.png)  A second possibility is to use the `windowed(`*n*`)`. This behaves similarly to `stopAndWait` but has an internal buffer of *n* items, which allows the `ControlledObservable` to run somewhat ahead of the observer from time to time. `windowed(1)` is equivalent to `stopAndWait`. 

   There are also two operators that convert an ordinary Observable into at `PausableObservable`. 

  ![pausable](http://reactivex.io/documentation/operators/images/bp.pausable.png)  If you call the `pause` method of a `PausableObservable` created with the `pausable` operator, it will drop (ignore) any items emitted by the underlying source Observable until such time as you call its `resume` method, whereupon it will continue to pass along emitted items to its observers. 

 #### See Also

 * [RxMarbles: `pausable`](http://rxmarbles.com/#pausable)

    ![pausableBuffered](http://reactivex.io/documentation/operators/images/bp.pausableBuffered.png)  If you call the `pause` method of a `PausableObservable` created with the `pausableBuffered` operator, it will buffer any items emitted by the underlying source Observable until such time as you call its `resume` method, whereupon it will emit those buffered items and then continue to pass along any additional emitted items to its observers. 

 #### See Also

 * [RxMarbles: `pausableBuffered`](http://rxmarbles.com/#pausableBuffered)

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/backpressure.html>

Introduction
============

 Each language-specific implementation of ReactiveX implements a set of operators. Although there is much overlap between implementations, there are also some operators that are only implemented in certain implementations. Also, each implementation tends to name its operators to resemble those of similar methods that are already familiar from other contexts in that language.

 Chaining Operators
------------------

 Most operators operate on an Observable and return an Observable. This allows you to apply these operators one after the other, in a chain. Each operator in the chain modifies the Observable that results from the operation of the previous operator.

 There are other patterns, like the Builder Pattern, in which a variety of methods of a particular class operate on an item of that same class by modifying that object through the operation of the method. These patterns also allow you to chain the methods in a similar way. But while in the Builder Pattern, the order in which the methods appear in the chain does not usually matter, with the Observable operators *order matters*.

 A chain of Observable operators do not operate independently on the original Observable that originates the chain, but they operate *in turn*, each one operating on the Observable generated by the operator immediately previous in the chain.

 The Operators of ReactiveX
--------------------------

 This page first lists what could be considered the “core” operators in ReactiveX, and links to pages that have more in-depth information on how these operators work and how particular language-specific ReactiveX versions have implemented these operators.

 Next is a “decision tree” that may help you choose the operator that is most appropriate to your use case.

 Finally, there is an alphabetical list of most of the operators available in the many language-specific implementations of ReactiveX. These link to the page that documents the core operator that most closely resembles the language-specific operator (so, for instance, the Rx.NET “SelectMany” operator links to the documentation of the FlatMap ReactiveX operator, of which “SelectMany” is the Rx.NET implementation).

 If you want to implement your own operator, see [Implementing Your Own Operators](implement-operator).

 #### Contents

 1. [Operators By Category](#categorized)
2. [A Decision Tree of Observable Operators](#tree)
3. [An Alphabetical List of Observable Operators](#alphabetical)

 Operators By Category
---------------------

 Creating Observables
--------------------

 Operators that originate new Observables.

 * [`Create`](operators/create) — create an Observable from scratch by calling observer methods programmatically
* [`Defer`](operators/defer) — do not create the Observable until the observer subscribes, and create a fresh Observable for each observer
* [`Empty`/`Never`/`Throw`](operators/empty-never-throw) — create Observables that have very precise and limited behavior
* [`From`](operators/from) — convert some other object or data structure into an Observable
* [`Interval`](operators/interval) — create an Observable that emits a sequence of integers spaced by a particular time interval
* [`Just`](operators/just) — convert an object or a set of objects into an Observable that emits that or those objects
* [`Range`](operators/range) — create an Observable that emits a range of sequential integers
* [`Repeat`](operators/repeat) — create an Observable that emits a particular item or sequence of items repeatedly
* [`Start`](operators/start) — create an Observable that emits the return value of a function
* [`Timer`](operators/timer) — create an Observable that emits a single item after a given delay

 Transforming Observables
------------------------

 Operators that transform items that are emitted by an Observable.

 * [`Buffer`](operators/buffer) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time
* [`FlatMap`](operators/flatmap) — transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
* [`GroupBy`](operators/groupby) — divide an Observable into a set of Observables that each emit a different group of items from the original Observable, organized by key
* [`Map`](operators/map) — transform the items emitted by an Observable by applying a function to each item
* [`Scan`](operators/scan) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value
* [`Window`](operators/window) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time

 Filtering Observables
---------------------

 Operators that selectively emit items from a source Observable.

 * [`Debounce`](operators/debounce) — only emit an item from an Observable if a particular timespan has passed without it emitting another item
* [`Distinct`](operators/distinct) — suppress duplicate items emitted by an Observable
* [`ElementAt`](operators/elementat) — emit only item *n* emitted by an Observable
* [`Filter`](operators/filter) — emit only those items from an Observable that pass a predicate test
* [`First`](operators/first) — emit only the first item, or the first item that meets a condition, from an Observable
* [`IgnoreElements`](operators/ignoreelements) — do not emit any items from an Observable but mirror its termination notification
* [`Last`](operators/last) — emit only the last item emitted by an Observable
* [`Sample`](operators/sample) — emit the most recent item emitted by an Observable within periodic time intervals
* [`Skip`](operators/skip) — suppress the first *n* items emitted by an Observable
* [`SkipLast`](operators/skiplast) — suppress the last *n* items emitted by an Observable
* [`Take`](operators/take) — emit only the first *n* items emitted by an Observable
* [`TakeLast`](operators/takelast) — emit only the last *n* items emitted by an Observable

 Combining Observables
---------------------

 Operators that work with multiple source Observables to create a single Observable

 * [`And`/`Then`/`When`](operators/and-then-when) — combine sets of items emitted by two or more Observables by means of `Pattern` and `Plan` intermediaries
* [`CombineLatest`](operators/combinelatest) — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function
* [`Join`](operators/join) — combine items emitted by two Observables whenever an item from one Observable is emitted during a time window defined according to an item emitted by the other Observable
* [`Merge`](operators/merge) — combine multiple Observables into one by merging their emissions
* [`StartWith`](operators/startwith) — emit a specified sequence of items before beginning to emit the items from the source Observable
* [`Switch`](operators/switch) — convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables
* [`Zip`](operators/zip) — combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function

 Error Handling Operators
------------------------

 Operators that help to recover from error notifications from an Observable

 * [`Catch`](operators/catch) — recover from an `onError` notification by continuing the sequence without error
* [`Retry`](operators/retry) — if a source Observable sends an `onError` notification, resubscribe to it in the hopes that it will complete without error

 Observable Utility Operators
----------------------------

 A toolbox of useful Operators for working with Observables

 * [`Delay`](operators/delay) — shift the emissions from an Observable forward in time by a particular amount
* [`Do`](operators/do) — register an action to take upon a variety of Observable lifecycle events
* [`Materialize`/`Dematerialize`](operators/materialize-dematerialize) — represent both the items emitted and the notifications sent as emitted items, or reverse this process
* [`ObserveOn`](operators/observeon) — specify the scheduler on which an observer will observe this Observable
* [`Serialize`](operators/serialize) — force an Observable to make serialized calls and to be well-behaved
* [`Subscribe`](operators/subscribe) — operate upon the emissions and notifications from an Observable
* [`SubscribeOn`](operators/subscribeon) — specify the scheduler an Observable should use when it is subscribed to
* [`TimeInterval`](operators/timeinterval) — convert an Observable that emits items into one that emits indications of the amount of time elapsed between those emissions
* [`Timeout`](operators/timeout) — mirror the source Observable, but issue an error notification if a particular period of time elapses without any emitted items
* [`Timestamp`](operators/timestamp) — attach a timestamp to each item emitted by an Observable
* [`Using`](operators/using) — create a disposable resource that has the same lifespan as the Observable

 Conditional and Boolean Operators
---------------------------------

 Operators that evaluate one or more Observables or items emitted by Observables

 * [`All`](operators/all) — determine whether all items emitted by an Observable meet some criteria
* [`Amb`](operators/amb) — given two or more source Observables, emit all of the items from only the first of these Observables to emit an item
* [`Contains`](operators/contains) — determine whether an Observable emits a particular item or not
* [`DefaultIfEmpty`](operators/defaultifempty) — emit items from the source Observable, or a default item if the source Observable emits nothing
* [`SequenceEqual`](operators/sequenceequal) — determine whether two Observables emit the same sequence of items
* [`SkipUntil`](operators/skipuntil) — discard items emitted by an Observable until a second Observable emits an item
* [`SkipWhile`](operators/skipwhile) — discard items emitted by an Observable until a specified condition becomes false
* [`TakeUntil`](operators/takeuntil) — discard items emitted by an Observable after a second Observable emits an item or terminates
* [`TakeWhile`](operators/takewhile) — discard items emitted by an Observable after a specified condition becomes false

 Mathematical and Aggregate Operators
------------------------------------

 Operators that operate on the entire sequence of items emitted by an Observable

 * [`Average`](operators/average) — calculates the average of numbers emitted by an Observable and emits this average
* [`Concat`](operators/concat) — emit the emissions from two or more Observables without interleaving them
* [`Count`](operators/count) — count the number of items emitted by the source Observable and emit only this value
* [`Max`](operators/max) — determine, and emit, the maximum-valued item emitted by an Observable
* [`Min`](operators/min) — determine, and emit, the minimum-valued item emitted by an Observable
* [`Reduce`](operators/reduce) — apply a function to each item emitted by an Observable, sequentially, and emit the final value
* [`Sum`](operators/sum) — calculate the sum of numbers emitted by an Observable and emit this sum

 Backpressure Operators
----------------------

 * [**backpressure operators**](operators/backpressure) — strategies for coping with Observables that produce items more rapidly than their observers consume them

 Connectable Observable Operators
--------------------------------

 Specialty Observables that have more precisely-controlled subscription dynamics

 * [`Connect`](operators/connect) — instruct a connectable Observable to begin emitting items to its subscribers
* [`Publish`](operators/publish) — convert an ordinary Observable into a connectable Observable
* [`RefCount`](operators/refcount) — make a Connectable Observable behave like an ordinary Observable
* [`Replay`](operators/replay) — ensure that all observers see the same sequence of emitted items, even if they subscribe after the Observable has begun emitting items

 Operators to Convert Observables
--------------------------------

 * [`To`](operators/to) — convert an Observable into another object or data structure

 A Decision Tree of Observable Operators
---------------------------------------


  This tree can help you find the ReactiveX Observable operator you’re looking for. 

  I want to create a new Observable  that emits a particular item [Just](operators/just)  that was returned from a function called at subscribe-time [Start](operators/start) that was returned from an `Action`, `Callable`, `Runnable`, or something of that sort, called at subscribe-time [From](operators/from) after a specified delay [Timer](operators/timer)  that pulls its emissions from a particular `Array`, `Iterable`, or something like that [From](operators/from) by retrieving it from a Future [Start](operators/start) that obtains its sequence from a Future [From](operators/from) that emits a sequence of items repeatedly [Repeat](operators/repeat) from scratch, with custom logic [Create](operators/create) for each observer that subscribes [Defer](operators/defer) that emits a sequence of integers [Range](operators/range)  at particular intervals of time [Interval](operators/interval)  after a specified delay [Timer](operators/timer)   that completes without emitting items [Empty](operators/empty-never-throw) that does nothing at all [Never](operators/empty-never-throw)  I want to create an Observable by combining other Observables  and emitting all of the items from all of the Observables in whatever order they are received [Merge](operators/merge) and emitting all of the items from all of the Observables, one Observable at a time [Concat](operators/concat) by combining the items from two or more Observables sequentially to come up with new items to emit  whenever *each* of the Observables has emitted a new item [Zip](operators/zip) whenever *any* of the Observables has emitted a new item [CombineLatest](operators/combinelatest) whenever an item is emitted by one Observable in a window defined by an item emitted by another [Join](operators/join) by means of `Pattern` and `Plan` intermediaries [And/Then/When](operators/and-then-when)  and emitting the items from only the most-recently emitted of those Observables [Switch](operators/switch)  I want to emit the items from an Observable after transforming them  one at a time with a function [Map](operators/map) by emitting all of the items emitted by corresponding Observables [FlatMap](operators/flatmap)  one Observable at a time, in the order they are emitted [ConcatMap](operators/flatmap)  based on all of the items that preceded them [Scan](operators/scan) by attaching a timestamp to them [Timestamp](operators/timestamp) into an indicator of the amount of time that lapsed before the emission of the item [TimeInterval](operators/timeinterval)  I want to shift the items emitted by an Observable forward in time before reemitting them [Delay](operators/delay) I want to transform items *and* notifications from an Observable into items and reemit them  by wrapping them in `Notification` objects [Materialize](operators/materialize-dematerialize)  which I can then unwrap again with [Dematerialize](operators/materialize-dematerialize)   I want to ignore all items emitted by an Observable and only pass along its completed/error notification [IgnoreElements](operators/ignoreelements) I want to mirror an Observable but prefix items to its sequence [StartWith](operators/startwith)  only if its sequence is empty [DefaultIfEmpty](operators/defaultifempty)  I want to collect items from an Observable and reemit them as buffers of items [Buffer](operators/buffer)  containing only the last items emitted [TakeLastBuffer](operators/takelast)  I want to split one Observable into multiple Observables [Window](operators/window)  so that similar items end up on the same Observable [GroupBy](operators/groupby)  I want to retrieve a particular item emitted by an Observable:  the last item emitted before it completed [Last](operators/last) the sole item it emitted [Single](operators/first) the first item it emitted [First](operators/first)  I want to reemit only certain items from an Observable  by filtering out those that do not match some predicate [Filter](operators/filter) that is, only the first item [First](operators/first) that is, only the first item*s*
 [Take](operators/take) that is, only the last item [Last](operators/last) that is, only item *n*
 [ElementAt](operators/elementat) that is, only those items after the first items  that is, after the first *n* items [Skip](operators/skip) that is, until one of those items matches a predicate [SkipWhile](operators/skipwhile) that is, after an initial period of time [Skip](operators/skip) that is, after a second Observable emits an item [SkipUntil](operators/skipuntil)  that is, those items except the last items  that is, except the last *n* items [SkipLast](operators/skiplast) that is, until one of those items matches a predicate [TakeWhile](operators/takewhile) that is, except items emitted during a period of time before the source completes [SkipLast](operators/skiplast) that is, except items emitted after a second Observable emits an item [TakeUntil](operators/takeuntil)  by sampling the Observable periodically [Sample](operators/sample) by only emitting items that are not followed by other items within some duration [Debounce](operators/debounce) by suppressing items that are duplicates of already-emitted items [Distinct](operators/distinct)  if they immediately follow the item they are duplicates of [DistinctUntilChanged](operators/distinct)  by delaying my subscription to it for some time after it begins emitting items [DelaySubscription](operators/delay)  I want to reemit items from an Observable only on condition that it was the first of a collection of Observables to emit an item [Amb](operators/amb) I want to evaluate the entire sequence of items emitted by an Observable  and emit a single boolean indicating if *all* of the items pass some test [All](operators/all) and emit a single boolean indicating if the Observable emitted *any* item (that passes some test) [Contains](operators/contains) and emit a single boolean indicating if the Observable emitted *no* items [IsEmpty](operators/contains) and emit a single boolean indicating if the sequence is identical to one emitted by a second Observable [SequenceEqual](operators/sequenceequal) and emit the average of all of their values [Average](operators/average) and emit the sum of all of their values [Sum](operators/sum) and emit a number indicating how many items were in the sequence [Count](operators/count) and emit the item with the maximum value [Max](operators/max) and emit the item with the minimum value [Min](operators/min) by applying an aggregation function to each item in turn and emitting the result [Scan](operators/scan)  I want to convert the entire sequence of items emitted by an Observable into some other data structure [To](operators/to) I want an operator to operate on a particular [Scheduler](http://reactivex.io/scheduler.html)
 [SubscribeOn](operators/subscribeon)  when it notifies observers [ObserveOn](operators/observeon)  I want an Observable to invoke a particular action when certain events occur [Do](operators/do) I want an Observable that will notify observers of an error [Throw](operators/empty-never-throw)  if a specified period of time elapses without it emitting an item [Timeout](operators/timeout)  I want an Observable to recover gracefully  from a timeout by switching to a backup Observable [Timeout](operators/timeout) from an upstream error notification [Catch](operators/catch)  by attempting to resubscribe to the upstream Observable [Retry](operators/retry)   I want to create a resource that has the same lifespan as the Observable [Using](operators/using) I want to subscribe to an Observable and receive a `Future` that blocks until the Observable completes [Start](operators/start) I want an Observable that does not start emitting items to subscribers until asked [Publish](operators/publish)  and then only emits the last item in its sequence [PublishLast](operators/publish) and then emits the complete sequence, even to those who subscribe after the sequence has begun [Replay](operators/replay) but I want it to go away once all of its subscribers unsubscribe [RefCount](operators/refcount) and then I want to ask it to start [Connect](operators/connect)    #### See Also

 * [Which Operator do I use?](http://xgrommx.github.io/rx-book/content/which_operator_do_i_use/index.html) by Dennis Stoyanov (a similar decision tree, specific to RxJS operators)

 An Alphabetical List of Observable Operators
--------------------------------------------

 Canonical, core operator names are in **boldface**. Other entries represent language-specific variants of these operators or specialty operators outside of the main ReactiveX core set of operators.

 * [`Aggregate`](operators/reduce)
* [`All`](operators/all)
* [`Amb`](operators/amb)
* [`ambArray`](operators/amb)
* [`ambWith`](operators/amb)
* [`and_`](operators/and-then-when)
* [`And`](operators/and-then-when)
* [`Any`](operators/contains)
* [`apply`](operators/create)
* [`as_blocking`](operators/to)
* [`asObservable`](operators/from)
* [`AssertEqual`](operators/sequenceequal)
* [`asyncAction`](operators/start)
* [`asyncFunc`](operators/start)
* [`Average`](operators/average)
* [`averageDouble`](operators/average)
* [`averageFloat`](operators/average)
* [`averageInteger`](operators/average)
* [`averageLong`](operators/average)
* [`blocking`](operators/to)
* [`blockingFirst`](operators/first)
* [`blockingForEach`](operators/subscribe)
* [`blockingIterable`](operators/to)
* [`blockingLast`](operators/last)
* [`blockingLatest`](operators/to)
* [`blockingMostRecent`](operators/to)
* [`blockingNext`](operators/to)
* [`blockingSingle`](operators/first)
* [`blockingSubscribe`](operators/subscribe)
* [`Buffer`](operators/buffer)
* [`bufferWithCount`](operators/buffer)
* [`bufferWithTime`](operators/buffer)
* [`bufferWithTimeOrCount`](operators/buffer)
* [`byLine`](operators/map)
* [`cache`](operators/replay)
* [`cacheWithInitialCapacity`](operators/replay)
* [`case`](operators/defer)
* [`Cast`](operators/map)
* [`Catch`](operators/catch)
* [`catchError`](operators/catch)
* [`catchException`](operators/catch)
* [`collect`](operators/reduce)
* [`collect`](operators/filter) (RxScala version of **`Filter`**)
* [`collectInto`](operators/reduce)
* [`CombineLatest`](operators/combinelatest)
* [`combineLatestDelayError`](operators/combinelatest)
* [`combineLatestWith`](operators/combinelatest)
* [`Concat`](operators/concat)
* [`concat_all`](operators/flatmap)
* [`concatAll`](operators/concat)
* [`concatArray`](operators/concat)
* [`concatArrayDelayError`](operators/concat)
* [`concatArrayEager`](operators/concat)
* [`concatDelayError`](operators/concat)
* [`concatEager`](operators/concat)
* [`concatMap`](operators/flatmap)
* [`concatMapDelayError`](operators/flatmap)
* [`concatMapEager`](operators/flatmap)
* [`concatMapEagerDelayError`](operators/flatmap)
* [`concatMapIterable`](operators/flatmap)
* [`concatMapObserver`](operators/flatmap)
* [`concatMapTo`](operators/flatmap)
* [`concatWith`](operators/concat)
* [`Connect`](operators/connect)
* [`connect_forever`](operators/connect)
* [`cons`](operators/startwith)
* [`Contains`](operators/contains)
* [`controlled`](operators/backpressure)
* [`Count`](operators/count)
* [`countLong`](operators/count)
* [`Create`](operators/create)
* [`cycle`](operators/repeat)
* [`Debounce`](operators/debounce)
* [`decode`](operators/from)
* [`DefaultIfEmpty`](operators/defaultifempty)
* [`Defer`](operators/defer)
* [`deferFuture`](operators/start)
* [`Delay`](operators/delay)
* [`delaySubscription`](operators/delay)
* [`delayWithSelector`](operators/delay)
* [`Dematerialize`](operators/materialize-dematerialize)
* [`Distinct`](operators/distinct)
* [`distinctKey`](operators/distinct)
* [`distinctUntilChanged`](operators/distinct)
* [`distinctUntilKeyChanged`](operators/distinct)
* [`Do`](operators/do)
* [`doAction`](operators/do)
* [`doAfterTerminate`](operators/do)
* [`doOnComplete`](operators/do)
* [`doOnCompleted`](operators/do)
* [`doOnDispose`](operators/do)
* [`doOnEach`](operators/do)
* [`doOnError`](operators/do)
* [`doOnLifecycle`](operators/do)
* [`doOnNext`](operators/do)
* [`doOnRequest`](operators/do)
* [`doOnSubscribe`](operators/do)
* [`doOnTerminate`](operators/do)
* [`doOnUnsubscribe`](operators/do)
* [`doseq`](operators/subscribe)
* [`doWhile`](operators/repeat)
* [`drop`](operators/skip)
* [`dropRight`](operators/skiplast)
* [`dropUntil`](operators/skipuntil)
* [`dropWhile`](operators/skipwhile)
* [`ElementAt`](operators/elementat)
* [`ElementAtOrDefault`](operators/elementat)
* [`Empty`](operators/empty-never-throw)
* [`emptyObservable`](operators/empty-never-throw)
* [`empty?`](operators/contains)
* [`encode`](operators/map)
* [`ensures`](operators/do)
* [`error`](operators/empty-never-throw)
* [`every`](operators/all)
* [`exclusive`](operators/switch)
* [`exists`](operators/contains)
* [`expand`](operators/flatmap)
* [`failWith`](operators/empty-never-throw)
* [`Filter`](operators/filter)
* [`filterNot`](operators/filter)
* [`Finally`](operators/do)
* [`finallyAction`](operators/do)
* [`finallyDo`](operators/do)
* [`find`](operators/contains)
* [`findIndex`](operators/contains)
* [`First`](operators/first)
* [`firstElement`](operators/first)
* [`FirstOrDefault`](operators/first)
* [`firstOrElse`](operators/first)
* [`FlatMap`](operators/flatmap)
* [`flatMapFirst`](operators/flatmap)
* [`flatMapIterable`](operators/flatmap)
* [`flatMapIterableWith`](operators/flatmap)
* [`flatMapLatest`](operators/flatmap)
* [`flatMapObserver`](operators/flatmap)
* [`flatMapWith`](operators/flatmap)
* [`flatMapWithMaxConcurrent`](operators/flatmap)
* [`flat_map_with_index`](operators/flatmap)
* [`flatten`](operators/merge)
* [`flattenDelayError`](operators/merge)
* [`foldl`](operators/reduce)
* [`foldLeft`](operators/reduce)
* [`for`](operators/flatmap)
* [`forall`](operators/all)
* [`ForEach`](operators/subscribe)
* [`forEachFuture`](operators/start)
* [`forEachWhile`](operators/subscribe)
* [`forIn`](operators/flatmap)
* [`forkJoin`](operators/zip)
* [`From`](operators/from)
* [`fromAction`](operators/from)
* [`fromArray`](operators/from)
* [`FromAsyncPattern`](operators/from)
* [`fromCallable`](operators/from)
* [`fromCallback`](operators/from)
* [`FromEvent`](operators/from)
* [`FromEventPattern`](operators/from)
* [`fromFunc0`](operators/from)
* [`fromFuture`](operators/from)
* [`fromIterable`](operators/from)
* [`fromIterator`](operators/from)
* [`from_list`](operators/from)
* [`fromNodeCallback`](operators/from)
* [`fromPromise`](operators/from)
* [`fromPublisher`](operators/from)
* [`fromRunnable`](operators/from)
* [`Generate`](operators/create)
* [`generateWithAbsoluteTime`](operators/create)
* [`generateWithRelativeTime`](operators/create)
* [`generator`](operators/create)
* [`GetEnumerator`](operators/to)
* [`getIterator`](operators/to)
* [`GroupBy`](operators/groupby)
* [`GroupByUntil`](operators/groupby)
* [`GroupJoin`](operators/join)
* [`head`](operators/first)
* [`headOption`](operators/first)
* [`headOrElse`](operators/first)
* [`if`](operators/defer)
* [`ifThen`](operators/defer)
* [`IgnoreElements`](operators/ignoreelements)
* [`indexOf`](operators/contains)
* [`interleave`](operators/merge)
* [`interpose`](operators/to)
* [`Interval`](operators/interval)
* [`intervalRange`](operators/range)
* [`into`](operators/reduce)
* [`isEmpty`](operators/contains)
* [`items`](operators/just)
* [`Join`](operators/join)
* [`join`](operators/sum) (string)
* [`jortSort`](operators/all)
* [`jortSortUntil`](operators/all)
* [`Just`](operators/just)
* [`keep`](operators/map)
* [`keep-indexed`](operators/map)
* [`Last`](operators/last)
* [`lastElement`](operators/last)
* [`lastOption`](operators/last)
* [`LastOrDefault`](operators/last)
* [`lastOrElse`](operators/last)
* [`Latest`](operators/first)
* [`latest`](operators/switch) (Rx.rb version of **`Switch`**)
* [`length`](operators/count)
* [`let`](operators/publish)
* [`letBind`](operators/publish)
* [`lift`](implement-operator)
* [`limit`](operators/take)
* [`LongCount`](operators/count)
* [`ManySelect`](operators/flatmap)
* [`Map`](operators/map)
* [`map`](operators/zip) (RxClojure version of **`Zip`**)
* [`MapCat`](operators/flatmap)
* [`mapCat`](operators/zip) (RxClojure version of **`Zip`**)
* [`map-indexed`](operators/map)
* [`mapTo`](operators/map)
* [`mapWithIndex`](operators/map)
* [`Materialize`](operators/materialize-dematerialize)
* [`Max`](operators/max)
* [`MaxBy`](operators/max)
* [`Merge`](operators/merge)
* [`mergeAll`](operators/merge)
* [`mergeArray`](operators/merge)
* [`mergeArrayDelayError`](operators/merge)
* [`merge_concurrent`](operators/merge)
* [`mergeDelayError`](operators/merge)
* [`mergeObservable`](operators/merge)
* [`mergeWith`](operators/merge)
* [`Min`](operators/min)
* [`MinBy`](operators/min)
* [`MostRecent`](operators/first)
* [`Multicast`](operators/publish)
* [`multicastWithSelector`](operators/publish)
* [`nest`](operators/to)
* [`Never`](operators/empty-never-throw)
* [`Next`](operators/takelast)
* [`Next`](operators/first) (BlockingObservable version)
* [`none`](operators/contains)
* [`nonEmpty`](operators/contains)
* [`nth`](operators/elementat)
* [`ObserveOn`](operators/observeon)
* [`ObserveOnDispatcher`](operators/observeon)
* [`observeSingleOn`](operators/observeon)
* [`of`](operators/from)
* [`of_array`](operators/from)
* [`ofArrayChanges`](operators/from)
* [`of_enumerable`](operators/from)
* [`of_enumerator`](operators/from)
* [`ofObjectChanges`](operators/from)
* [`OfType`](operators/filter)
* [`ofWithScheduler`](operators/from)
* [`onBackpressureBlock`](operators/backpressure)
* [`onBackpressureBuffer`](operators/backpressure)
* [`onBackpressureDrop`](operators/backpressure)
* [`OnErrorResumeNext`](operators/catch)
* [`onErrorReturn`](operators/catch)
* [`onErrorReturnItem`](operators/catch)
* [`onExceptionResumeNext`](operators/catch)
* [`onTerminateDetach`](operators/do)
* [`orElse`](operators/defaultifempty)
* [`pairs`](operators/from)
* [`pairwise`](operators/buffer)
* [`partition`](operators/groupby)
* [`partition-all`](operators/window)
* [`pausable`](operators/backpressure)
* [`pausableBuffered`](operators/backpressure)
* [`pluck`](operators/map)
* [`product`](operators/sum)
* [`Publish`](operators/publish)
* [`PublishLast`](operators/publish)
* [`publish_synchronized`](operators/replay)
* [`publishValue`](operators/publish)
* [`raise_error`](operators/empty-never-throw)
* [`Range`](operators/range)
* [`Reduce`](operators/reduce)
* [`reduceWith`](operators/reduce)
* [`reductions`](operators/scan)
* [`RefCount`](operators/refcount)
* [`Repeat`](operators/repeat)
* [`repeat_infinitely`](operators/repeat)
* [`repeatUntil`](operators/repeat)
* [`repeatWhen`](operators/repeat)
* [`Replay`](operators/replay)
* [`rescue_error`](operators/catch)
* [`rest`](operators/first)
* [`Retry`](operators/retry)
* [`retry_infinitely`](operators/retry)
* [`retryUntil`](operators/retry)
* [`retryWhen`](operators/retry)
* [`Return`](operators/just)
* [`returnElement`](operators/just)
* [`returnValue`](operators/just)
* [`runAsync`](operators/from)
* [`safeSubscribe`](operators/subscribe)
* [`Sample`](operators/sample)
* [`Scan`](operators/scan)
* [`scanWith`](operators/scan)
* [`scope`](operators/using)
* [`Select`](operators/map) (alternate name of **`Map`**)
* [`select`](operators/filter) (alternate name of **`Filter`**)
* [`selectConcat`](operators/flatmap)
* [`selectConcatObserver`](operators/flatmap)
* [`SelectMany`](operators/flatmap)
* [`selectManyObserver`](operators/flatmap)
* [`select_switch`](operators/switch)
* [`selectSwitch`](operators/flatmap)
* [`selectSwitchFirst`](operators/flatmap)
* [`selectWithMaxConcurrent`](operators/flatmap)
* [`select_with_index`](operators/filter)
* [`seq`](operators/from)
* [`SequenceEqual`](operators/sequenceequal)
* [`sequence_eql?`](operators/sequenceequal)
* [`SequenceEqualWith`](operators/sequenceequal)
* [`Serialize`](operators/serialize)
* [`share`](operators/refcount)
* [`shareReplay`](operators/replay)
* [`shareValue`](operators/refcount)
* [`Single`](operators/first)
* [`singleElement`](operators/first)
* [`SingleOrDefault`](operators/first)
* [`singleOption`](operators/first)
* [`singleOrElse`](operators/first)
* [`size`](operators/count)
* [`Skip`](operators/skip)
* [`SkipLast`](operators/skiplast)
* [`skipLastWithTime`](operators/skiplast)
* [`SkipUntil`](operators/skipuntil)
* [`skipUntilWithTime`](operators/skipuntil)
* [`SkipWhile`](operators/skipwhile)
* [`skipWhileWithIndex`](operators/skipwhile)
* [`skip_with_time`](operators/skip)
* [`slice`](operators/filter)
* [`sliding`](operators/window)
* [`slidingBuffer`](operators/buffer)
* [`some`](operators/contains)
* [`sort`](operators/to)
* [`sorted`](operators/to)
* [`sort-by`](operators/to)
* [`sorted-list-by`](operators/to)
* [`split`](operators/flatmap)
* [`split-with`](operators/groupby)
* [`Start`](operators/start)
* [`startAsync`](operators/start)
* [`startFuture`](operators/start)
* [`StartWith`](operators/startwith)
* [`startWithArray`](operators/startwith)
* [`stringConcat`](operators/sum)
* [`stopAndWait`](operators/backpressure)
* [`subscribe`](operators/subscribe)
* [`subscribeActual`](operators/subscribe)
* [`SubscribeOn`](operators/subscribeon)
* [`SubscribeOnDispatcher`](operators/subscribeon)
* [`subscribeOnCompleted`](operators/subscribe)
* [`subscribeOnError`](operators/subscribe)
* [`subscribeOnNext`](operators/subscribe)
* [`subscribeWith`](operators/subscribe)
* [`Sum`](operators/sum)
* [`sumDouble`](operators/sum)
* [`sumFloat`](operators/sum)
* [`sumInteger`](operators/sum)
* [`sumLong`](operators/sum)
* [`Switch`](operators/switch)
* [`switchCase`](operators/defer)
* [`switchIfEmpty`](operators/defaultifempty)
* [`switchLatest`](operators/switch)
* [`switchMap`](operators/flatmap)
* [`switchMapDelayError`](operators/flatmap)
* [`switchOnNext`](operators/switch)
* [`switchOnNextDelayError`](operators/switch)
* [`Synchronize`](operators/serialize)
* [`Take`](operators/take)
* [`take_with_time`](operators/take)
* [`takeFirst`](operators/first)
* [`TakeLast`](operators/takelast)
* [`takeLastBuffer`](operators/takelast)
* [`takeLastBufferWithTime`](operators/takelast)
* [`takeLastWithTime`](operators/takelast)
* [`takeRight`](operators/last) (see also: [`TakeLast`](operators/takelast))
* [`TakeUntil`](operators/takeuntil)
* [`takeUntilWithTime`](operators/takeuntil)
* [`TakeWhile`](operators/takewhile)
* [`takeWhileWithIndex`](operators/takewhile)
* [`tail`](operators/takelast)
* [`tap`](operators/do)
* [`tapOnCompleted`](operators/do)
* [`tapOnError`](operators/do)
* [`tapOnNext`](operators/do)
* [`Then`](operators/and-then-when)
* [`thenDo`](operators/and-then-when)
* [`Throttle`](operators/debounce)
* [`throttleFirst`](operators/sample)
* [`throttleLast`](operators/sample)
* [`throttleWithSelector`](operators/debounce)
* [`throttleWithTimeout`](operators/debounce)
* [`Throw`](operators/empty-never-throw)
* [`throwError`](operators/empty-never-throw)
* [`throwException`](operators/empty-never-throw)
* [`TimeInterval`](operators/timeinterval)
* [`Timeout`](operators/timeout)
* [`timeoutWithSelector`](operators/timeout)
* [`Timer`](operators/timer)
* [`Timestamp`](operators/timestamp)
* [`To`](operators/to)
* [`to_a`](operators/to)
* [`ToArray`](operators/to)
* [`ToAsync`](operators/start)
* [`toBlocking`](operators/to)
* [`toBuffer`](operators/to)
* [`to_dict`](operators/to)
* [`ToDictionary`](operators/to)
* [`ToEnumerable`](operators/to)
* [`ToEvent`](operators/to)
* [`ToEventPattern`](operators/to)
* [`ToFlowable`](operators/to)
* [`ToFuture`](operators/to)
* [`to_h`](operators/to)
* [`toIndexedSeq`](operators/to)
* [`toIterable`](operators/to)
* [`toIterator`](operators/to)
* [`ToList`](operators/to)
* [`ToLookup`](operators/to)
* [`toMap`](operators/to)
* [`toMultiMap`](operators/to)
* [`ToObservable`](operators/from)
* [`toSet`](operators/to)
* [`toSortedList`](operators/to)
* [`toStream`](operators/to)
* [`ToTask`](operators/to)
* [`toTraversable`](operators/to)
* [`toVector`](operators/to)
* [`tumbling`](operators/window)
* [`tumblingBuffer`](operators/buffer)
* [`unsafeCreate`](operators/create)
* [`unsubscribeOn`](operators/subscribeon)
* [`Using`](operators/using)
* [`When`](operators/and-then-when)
* [`Where`](operators/filter)
* [`while`](operators/repeat)
* [`whileDo`](operators/repeat)
* [`Window`](operators/window)
* [`windowWithCount`](operators/window)
* [`windowWithTime`](operators/window)
* [`windowWithTimeOrCount`](operators/window)
* [`windowed`](operators/backpressure)
* [`withFilter`](operators/filter)
* [`withLatestFrom`](operators/combinelatest)
* [`Zip`](operators/zip)
* [`zipArray`](operators/zip)
* [`zipIterable`](operators/zip)
* [`zipWith`](operators/zip)
* [`zipWithIndex`](operators/zip)
* [`++`](operators/concat)
* [`+:`](operators/startwith)
* [`:+`](operators/just)



 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators.html>

Create
======

 
> create an Observable from scratch by means of a function

  ![Create](http://reactivex.io/documentation/operators/images/create.c.png)  You can create an Observable from scratch by using the Create operator. You pass this operator a function that accepts the observer as its parameter. Write this function so that it behaves as an Observable — by calling the observer’s `onNext`, `onError`, and `onCompleted` methods appropriately. 


 A well-formed finite Observable must attempt to call either the observer’s `onCompleted` method exactly once or its `onError` method exactly once, and must not thereafter attempt to call any of the observer’s other methods. 

  #### See Also

 * [Introduction to Rx: Create](http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableCreate)
* [Introduction to Rx: Generate](http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableGenerate)
* [101 Rx Samples: Generate](http://rxwiki.wikidot.com/101samples#toc42)
* [RxJava Tutorial 03: Observable from, just, & create methods](https://www.youtube.com/watch?v=sDqrlNprY24)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `create`

     ![create](http://reactivex.io/documentation/operators/images/create.png)  RxGroovy implements this operator as `create`. 

 #### Sample Code

 
```
def myObservable = Observable.create({ aSubscriber ->
  try {
    for (int i = 1; i < 1000000; i++) {
      if (aSubscriber.isUnsubscribed()) {
        return;
      }
      aSubscriber.onNext(i);
    }
    if (!aSubscriber.isUnsubscribed()) {
      aSubscriber.onCompleted();
    }
  } catch(Throwable t) {
    if (!aSubscriber.isUnsubscribed()) {
      aSubscriber.onError(t);
    }
  }
})
```
  It is good practice to check the observer’s `isUnsubscribed` state so that your Observable can stop emitting items or doing expensive calculations when there is no longer an interested observer. 


 `create` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`create(OnSubscribe)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#create(rx.Observable.OnSubscribe))
       ###  RxJava 1․x `create`

     ![create](http://reactivex.io/documentation/operators/images/create.png)  RxJava implements this operator as `create`. 


 It is good practice to check the observer’s `isUnsubscribed` state from within the function you pass to `create` so that your Observable can stop emitting items or doing expensive calculations when there is no longer an interested observer. 

 #### Sample Code

 
```
Observable.create(new Observable.OnSubscribe<Integer>() {
    @Override
    public void call(Subscriber<? super Integer> observer) {
        try {
            if (!observer.isUnsubscribed()) {
                for (int i = 1; i < 5; i++) {
                    observer.onNext(i);
                }
                observer.onCompleted();
            }
        } catch (Exception e) {
            observer.onError(e);
        }
    }
 } ).subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Next: 2
Next: 3
Next: 4
Sequence complete.
```
  `create` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`create(OnSubscribe)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#create(rx.Observable.OnSubscribe))
       ###  RxJS `create createWithDisposable generate generateWithAbsoluteTime generateWithRelativeTime`

     ![create](http://reactivex.io/documentation/operators/images/create.png)  RxJS implements this operator as `create` (there is also an alternate name for the same operator: `createWithDisposable`). 

 #### Sample Code

 
```
/* Using a function */
var source = Rx.Observable.create(function (observer) {
    observer.onNext(42);
    observer.onCompleted();

    // Note that this is optional, you do not have to return this if you require no cleanup
    return function () { console.log('disposed'); };
});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 42
Completed
```
 
```
/* Using a disposable */
var source = Rx.Observable.create(function (observer) {
    observer.onNext(42);
    observer.onCompleted();

    // Note that this is optional, you do not have to return this if you require no cleanup
    return Rx.Disposable.create(function () {
        console.log('disposed');
    });
});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 42
Completed
```
  `create` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![generate](http://reactivex.io/documentation/operators/images/generate.png)  You can use the `generate` operator to create simple Observables that can generate their next emissions, and can determine when to terminate, based on the value of the previous emission. The basic form of `generate` takes four parameters: 


1. the first item to emit
2. a function to test an item to determine whether to emit it (`true`) or terminate the Observable (`false`)
3. a function to generate the next item to test and emit based on the value of the previous item
4. a function to transform items before emitting them


 You can also pass in as an optional fifth parameter a [Scheduler](../scheduler) that `generate` will use to create and emit its sequence (it uses `currentThread` by default). 

 #### Sample Code

 
```
var source = Rx.Observable.generate(
    0,
    function (x) { return x < 3; },
    function (x) { return x + 1; },
    function (x) { return x; }
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
  `generate` is found in the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![generateWithRelativeTime](http://reactivex.io/documentation/operators/images/generateWithRelativeTime.png)  You can use the `generateWithRelativeTime` operator to create simple Observables that can generate their next emissions, and can determine when to terminate, based on the value of the previous emission. The basic form of `generateWithRelativeTime` takes five parameters: 


1. the first item to emit
2. a function to test an item to determine whether to emit it (`true`) or terminate the Observable (`false`)
3. a function to generate the next item to test and emit based on the value of the previous item
4. a function to transform items before emitting them
5. a function to indicate how long, in milliseconds, the generator should wait after the emission of the previous item before emitting this item


 You can also pass in as an optional sixth parameter a [Scheduler](../scheduler) that `generate` will use to create and emit its sequence (it uses `currentThread` by default). 

 #### Sample Code

 
```
var source = Rx.Observable.generateWithRelativeTime(
    1,
    function (x) { return x < 4; },
    function (x) { return x + 1; },
    function (x) { return x; },
    function (x) { return 100 * x; }
).timeInterval();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: {value: 1, interval: 100}
Next: {value: 2, interval: 200}
Next: {value: 3, interval: 300}
Completed
```
  `generateWithRelativeTime` is found in the following distributions: 

 * `rx.lite.js`
* `rx.lite.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)

    ![generateWithAbsoluteTime](http://reactivex.io/documentation/operators/images/generateWithAbsoluteTime.png)  You can use the `generateWithAbsoluteTime` operator to create simple Observables that can generate their next emissions, and can determine when to terminate, based on the value of the previous emission. The basic form of `generateWithAbsoluteTime` takes five parameters: 


1. the first item to emit
2. a function to test an item to determine whether to emit it (`true`) or terminate the Observable (`false`)
3. a function to generate the next item to test and emit based on the value of the previous item
4. a function to transform items before emitting them
5. a function to indicate at what time (expressed as a `Date`) the generator should emit the the new item


 You can also pass in as an optional sixth parameter a [Scheduler](../scheduler) that `generate` will use to create and emit its sequence (it uses `currentThread` by default). 

 #### Sample Code

 
```
var source = Rx.Observable.generate(
    1,
    function (x) { return x < 4; },
    function (x) { return x + 1; },
    function (x) { return x; },
    function (x) { return Date.now() + (100 * x); }
).timeInterval();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: {value: 1, interval: 100}
Next: {value: 2, interval: 200}
Next: {value: 3, interval: 300}
Completed
```
  `generateWithAbsoluteTime` is found in the following distribution: 

 * `rx.time.js` (requires `rx.js` or `rx.compat.js`)

        ###  RxPHP `create`

       RxPHP implements this operator as `create`. 

  Creates an observable sequence from a specified subscribeAction callable implementation. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/create/create.php

//With static method
$source = \Rx\Observable::create(function (\Rx\ObserverInterface $observer) {
    $observer->onNext(42);
    $observer->onCompleted();

    return new CallbackDisposable(function () {
        echo "Disposed\n";
    });
});

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 42
Complete!
Disposed
```
         ###  RxSwift `create generate`

     ![create](http://reactivex.io/documentation/operators/images/create.png)  RxSwift implements this operator as `create`. 

 #### Sample Code

 
```
let source : Observable = Observable.create { observer in
    for i in 1...5 {
        observer.on(.next(i))
    }
    observer.on(.completed)

    // Note that this is optional. If you require no cleanup you can return
    // `Disposables.create()` (which returns the `NopDisposable` singleton)
    return Disposables.create {
        print("disposed")
    }
}

source.subscribe {
    print($0)
}
```
 
```
next(1)
next(2)
next(3)
next(4)
next(5)
completed
disposed
```
    ![generate](http://reactivex.io/documentation/operators/images/generate.png)  You can use the `generate` operator to create simple Observables that can generate their next emissions, and can determine when to terminate, based on the value of the previous emission. The basic form of `generate` takes three parameters: 


1. the first item to emit
2. a function to test an item to determine whether to emit it (`true`) or terminate the Observable (`false`)
3. a function to generate the next item to test and emit based on the value of the previous item


 You can also pass in as an optional fourth parameter a [Scheduler](../scheduler) that `generate` will use to create and emit its sequence (it uses `CurrentThreadScheduler` by default). 

 #### Sample Code

 
```
let source = Observable.generate(
   initialState: 0,
   condition: { $0 < 3 },
   iterate: { $0 + 1 }
)

source.subscribe {
   print($0)
}
```
 
```
next(0)
next(1)
next(2)
completed
```
      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/create.html>

Debounce
========

 
> only emit an item from an Observable if a particular timespan has passed without it emitting another item

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#debounce)  The Debounce operator filters out items emitted by the source Observable that are rapidly followed by another emitted item. 

  #### See Also

 * [Backpressure-related Operators](backpressure)
* [Sample](sample)
* [Window](window)
* [Introduction to Rx: Throttle](http://www.introtorx.com/Content/v1.0.10621.0/13_TimeShiftedSequences.html#Throttle)
* [RxMarbles: `debounce`](http://rxmarbles.com/#debounce)
* [RxMarbles: `debounceWithSelector`](http://rxmarbles.com/#debounceWithSelector)
* [101 Rx Samples: Throttle — Simple](http://rxwiki.wikidot.com/101samples#toc30)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `debounce throttleWithTimeout`

     RxGroovy implements this operator as `throttleWithTimeout` and `debounce`. 


 Note that the last item emitted by the source Observable will be emitted in turn by this operator even if the source Observable’s `onCompleted` notification is issued within the time window you specify since that item’s emission. That is to say: an `onCompleted` notification will not trigger a throttle. 

  ![debounce](http://reactivex.io/documentation/operators/images/debounce.png)  One variant of `throtleWithTimeout`/`debounce` (two names for the same operator variant) throttles at a periodic time interval that you choose by passing in a `TimeUnit` and a quantity of such units as parameters to the operator. 


 This variant operates by default on the `computation` [Scheduler](../scheduler), but you can optionally pass in a Scheduler of your choosing as a third parameter. 

 * Javadoc: [`throttleWithTimeout(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleWithTimeout(long,%20java.util.concurrent.TimeUnit)) and [`debounce(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#debounce(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`throttleWithTimeout(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleWithTimeout(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler)) and [`debounce(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#debounce(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![debounce](http://reactivex.io/documentation/operators/images/debounce.f.png)  There ia also a variant of `debounce` (that does not have a `throttleWithTimeout` alias) that throttles the source Observable by applying a function to each item it emits, this function generating an Observable. If the source Observable emits another item before this newly-generated Observable terminates, `debounce` will suppress the item. 


 This variant of `debounce` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`debounce(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#debounce(rx.functions.Func1))
       ###  RxJava 1․x `debounce throttleWithTimeout`

     RxJava implements this operator as `throttleWithTimeout` and `debounce`. 


 Note that the last item emitted by the source Observable will be emitted in turn by this operator even if the source Observable’s `onCompleted` notification is issued within the time window you specify since that item’s emission. That is to say: an `onCompleted` notification will not trigger a throttle. 

  ![debounce](http://reactivex.io/documentation/operators/images/debounce.png)  One variant of `throtleWithTimeout`/`debounce` (two names for the same operator variant) throttles at a periodic time interval that you choose by passing in a `TimeUnit` and a quantity of such units as parameters to the operator. 


 This variant operates by default on the `computation` [Scheduler](../scheduler), but you can optionally pass in a Scheduler of your choosing as a third parameter. 

 * Javadoc: [`throttleWithTimeout(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleWithTimeout(long,%20java.util.concurrent.TimeUnit)) and [`debounce(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#debounce(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`throttleWithTimeout(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleWithTimeout(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler)) and [`debounce(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#debounce(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![debounce](http://reactivex.io/documentation/operators/images/debounce.f.png)  There ia also a variant of `debounce` (that does not have a `throttleWithTimeout` alias) that throttles the source Observable by applying a function to each item it emits, this function generating an Observable. If the source Observable emits another item before this newly-generated Observable terminates, `debounce` will suppress the item. 


 This variant of `debounce` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`debounce(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#debounce(rx.functions.Func1))
       ###  RxJS `debounce debounceWithSelector throttleWithTimeout`

     ![debounce](http://reactivex.io/documentation/operators/images/debounce.png)  The first variant — called either `debounce` or `throttleWithTimeout` — accepts as its parameter a duration, defined as an integer number of milliseconds, and it suppresses any emitted items that are followed by other emitted items during that duration since the first item’s emission. 

 #### Sample Code

 
```
var times = [
    { value: 0, time: 100 },
    { value: 1, time: 600 },
    { value: 2, time: 400 },
    { value: 3, time: 700 },
    { value: 4, time: 200 }
];

// Delay each item by time and project value;
var source = Rx.Observable.from(times)
  .flatMap(function (item) {
    return Rx.Observable
      .of(item.value)
      .delay(item.time);
  })
  .debounce(500 /* ms */);

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });
```
 
```
Next: 0
Next: 2
Next: 4
Completed
```
    ![debounceWithSelector](http://reactivex.io/documentation/operators/images/debounceWithSelector.png)  The `debounceWithSelector` operator throttles the source Observable by applying a function to each item it emits, this function generating an Observable. If the source Observable emits another item before this newly-generated Observable terminates, `debounce` will suppress the item. 

 #### Sample Code

 
```
var array = [
    800,
    700,
    600,
    500
];

var source = Rx.Observable.for(
    array,
    function (x) {
        return Rx.Observable.timer(x)
    })
    .map(function(x, i) { return i; })
    .throttleWithSelector(function (x) {
        return Rx.Observable.timer(700);
    });

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 0
Next: 3
Completed
```
    `debounce` and `debounceWithSelector` are found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `throttle`

       RxPHP implements this operator as `throttle`. 

  Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. If items are emitted on the source observable prior to the expiration of the time period, the last item emitted on the source observable will be emitted. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/throttle/throttle.php

$times = [
    ['value' => 0, 'time' => 10],
    ['value' => 1, 'time' => 200],
    ['value' => 2, 'time' => 400],
    ['value' => 3, 'time' => 500],
    ['value' => 4, 'time' => 900]
];

// Delay each item by time and project value;
$source = Observable::fromArray($times)
    ->flatMap(function ($item) {
        return Observable::of($item['value'])
            ->delay($item['time']);
    })
    ->throttle(300 /* ms */);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 3
Next value: 4
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/debounce.html>

Delay
=====

 
> shift the emissions from an Observable forward in time by a particular amount

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#delay)  The Delay operator modifies its source Observable by pausing for a particular increment of time (that you specify) before emitting each of the source Observable’s items. This has the effect of shifting the entire sequence of items emitted by the Observable forward in time by that specified increment. 

  #### See Also

 * [Introduction to Rx: Delay](http://www.introtorx.com/Content/v1.0.10621.0/13_TimeShiftedSequences.html#Delay)
* [RxMarbles: `delay`](http://rxmarbles.com/#delay)
* [RxMarbles: `delayWithSelector`](http://rxmarbles.com/#delayWithSelector)
* [101 Rx Samples: Delay — Simple](http://rxwiki.wikidot.com/101samples#toc27)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `delay delaySubscription`

     RxGroovy implements this operator as variants of `delay` and `delaySubscription`. 

  ![delay](http://reactivex.io/documentation/operators/images/delay.png)  The first variant of `delay` accepts parameters that define a duration of time (a quantity of time, and a `TimeUnit` that this quantity is denominated in). Each time the source Observable emits an item, `delay` starts a timer, and when that timer reaches the given duration, the Observable returned from `delay` emits the same item. 


 Note that `delay` will not time-shift an `onError` notification in this fashion but it will forward such a notification immediately to its subscribers while dropping any pending `onNext` notifications. It will however time shift an `onCompleted` notification. 


 By default this variant of `delay` operates on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `delay` 

 * Javadoc: [`delay(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`delay()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![delay](http://reactivex.io/documentation/operators/images/delay.o.png)  Another variant of `delay` does not use a constant delay duration, but sets its delay duration on a per-item basis by passing each item from the source Observable into a function that returns an Observable and then monitoring those Observables. When any such Observable emits a item or completes, the Observable returned by `delay` emits the associated item. 


 This variant of `delay` does not by default run on any particular [Scheduler](../scheduler). 

 * Javadoc: [`delay(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(rx.functions.Func1))
   ![delay](http://reactivex.io/documentation/operators/images/delay.oo.png)  The variant of `delay` that uses a per-item Observable to set the delay has a variant that allows you to pass in a function that returns an Observable that acts as a delay timer for the subscription to the source Observable (in the absence of this, `delay` subscribes to the source Observable as soon as an observer subscribes to the Observable returned by `delay`). 


 This variant of `delay` does not by default run on any particular [Scheduler](../scheduler). 

 * Javadoc: [`delay(Func0,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(rx.functions.Func0,%20rx.functions.Func1))
   ![delaySubscription](http://reactivex.io/documentation/operators/images/delaySubscription.png)  There is also an operator with which you can delay the subscription to the source Observable: `delaySubscription`. It accepts parameters that define the amount of time to delay (a quantity of time, and a `TimeUnit` that this quantity is denominated in). 


 This variant of `delay` by default runs on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `delaySubscription`. 

 * Javadoc: [`delaySubscription(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delaySubscription(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`delaySubscription(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delaySubscription(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![delaySubscription](http://reactivex.io/documentation/operators/images/delaySubscription.o.png)  And there is a variant of `delaySubscription` that uses an Observable (returned by a function you supply) rather than a fixed duration in order to set the subscription delay. 


 This variant of `delaySubscription` does not by default run on any particular [Scheduler](../scheduler). 

 * Javadoc: [`delaySubscription(Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delaySubscription(rx.functions.Func0))
       ###  RxJava 1․x `delay delaySubscription`

     RxJava implements this operator as variants of `delay` and `delaySubscription`. 

  ![delay](http://reactivex.io/documentation/operators/images/delay.png)  The first variant of `delay` accepts parameters that define a duration of time (a quantity of time, and a `TimeUnit` that this quantity is denominated in). Each time the source Observable emits an item, `delay` starts a timer, and when that timer reaches the given duration, the Observable returned from `delay` emits the same item. 


 Note that `delay` will not time-shift an `onError` notification in this fashion but it will forward such a notification immediately to its subscribers while dropping any pending `onNext` notifications. It will however time shift an `onCompleted` notification. 


 By default this variant of `delay` operates on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `delay` 

 * Javadoc: [`delay(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`delay()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![delay](http://reactivex.io/documentation/operators/images/delay.o.png)  Another variant of `delay` does not use a constant delay duration, but sets its delay duration on a per-item basis by passing each item from the source Observable into a function that returns an Observable and then monitoring those Observables. When any such Observable emits an item or completes, the Observable returned by `delay` emits the associated item. 


 This variant of `delay` does not by default run on any particular [Scheduler](../scheduler). 

 * Javadoc: [`delay(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(rx.functions.Func1))
   ![delay](http://reactivex.io/documentation/operators/images/delay.oo.png)  The variant of `delay` that uses a per-item Observable to set the delay has a variant that allows you to pass in a function that returns an Observable that acts as a delay timer for the subscription to the source Observable (in the absence of this, `delay` subscribes to the source Observable as soon as an observer subscribes to the Observable returned by `delay`). 


 This variant of `delay` does not by default run on any particular [Scheduler](../scheduler). 

 * Javadoc: [`delay(Func0,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(rx.functions.Func0,%20rx.functions.Func1))
   ![delaySubscription](http://reactivex.io/documentation/operators/images/delaySubscription.png)  There is also an operator with which you can delay the subscription to the source Observable: `delaySubscription`. It accepts parameters that define the amount of time to delay (a quantity of time, and a `TimeUnit` that this quantity is denominated in). 


 This variant of `delay` by default runs on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `delaySubscription`. 

 * Javadoc: [`delaySubscription(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delaySubscription(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`delaySubscription(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delaySubscription(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![delaySubscription](http://reactivex.io/documentation/operators/images/delaySubscription.o.png)  And there is a variant of `delaySubscription` that uses an Observable (returned by a function you supply) rather than a fixed duration in order to set the subscription delay. 


 This variant of `delaySubscription` does not by default run on any particular [Scheduler](../scheduler). 

 * Javadoc: [`delaySubscription(Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#delaySubscription(rx.functions.Func0))
       ###  RxJS `delay delaySubscription delayWithSelector`

     ![delay](http://reactivex.io/documentation/operators/images/delay.png)  In RxJS you can set the per-item delay in two ways: by passing a number of milliseconds into the `delay` operator (which will delay each emission by that amount of time), or by passing in a `Date` object (which will delay the beginning of the sequence of emissions until that absolute point in time). 


 This operator operates by default on the `timeout` [Scheduler](../scheduler), but you can override this by passing in another Scheduler as an optional second parameter. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 3)
    .delay(new Date(Date.now() + 1000));

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x.toString()); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
 
```
var source = Rx.Observable.range(0, 3)
    .delay(1000);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x.toString()); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
   ![delaySubscription](http://reactivex.io/documentation/operators/images/delaySubscription.png)  `delaySubscription` is similar to `delay` but rather than timeshifting the emissions from the source Observable, it timeshifts the moment of subscription to that Observable. You pass to this operator a time value (either a `Number`, in which case this sets the number of milliseconds of delay, or a `Date`, in which case this sets an absolute future time at which `delaySubscription` will trigger the subscription). You may optionally pass a [Scheduler](../scheduler) as a second parameter, which `delaySubscription` will use to govern the delay period or trigger time. 

 #### Sample Code

 
```
var start = Date.now();
var source = Rx.Observable.range(0, 3).delaySubscription(5000);

var subscription = source.subscribe(
    function (x) { console.log('Next: %s, %s', x, Date.now() - start); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0, 5001
Next: 1, 5002
Next: 2, 5003
Completed
```
    ![delayWithSelector](http://reactivex.io/documentation/operators/images/delayWithSelector.png)  `delayWithSelector` is like `delay` but does not use a constant delay duration (or absolute time), but sets its delay duration on a per-item basis by passing each item from the source Observable into a function that returns an Observable and then monitoring those Observables. When any such Observable completes, the Observable returned by `delay` emits the associated item. 

 #### Sample Code

 
```
var source = Rx.Observable
    .range(0, 3)
    .delayWithSelector(
        function (x) {
            return Rx.Observable.timer(x * 400);
        })
    .timeInterval()
    .map(function (x) { return x.value + ':' + x.interval; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0:0
Next: 1:400
Next: 2:400
Completed
```
   ![delayWithSelector](http://reactivex.io/documentation/operators/images/delayWithSelector.o.png)  There is also a version of `delayWithSelector` that takes an additional (first) argument: an Observable that sets a delay before `delayWithSelector` subscribes to the source Observable after it itself is subscribed to. 

 #### Sample Code

 
```
var source = Rx.Observable
    .range(0, 3)
    .delayWithSelector(
        Rx.Observable.timer(300),
        function (x) {
            return Rx.Observable.timer(x * 400);
        }
    )
    .timeInterval()
    .map(function (x) { return x.value + ':' + x.interval; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0:300
Next: 1:400
Next: 2:400
Completed
```
   `delay`, `delaySubscription`, and `delayWithSelector` require `rx.lite.js` or `rx.lite.compat.js` and are found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)

      ###  RxPHP `delay`

       RxPHP implements this operator as `delay`. 

  Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/delay/delay.php

\Rx\Observable::interval(1000)
    ->doOnNext(function ($x) {
        echo 'Side effect: ' . $x . "\n";
    })
    ->delay(500)
    ->take(5)
    ->subscribe($createStdoutObserver());
```
  
```
Side effect: 0
Next value: 0
Side effect: 1
Next value: 1
Side effect: 2
Next value: 2
Side effect: 3
Next value: 3
Side effect: 4
Next value: 4
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/delay.html>

Interval
========

 
> create an Observable that emits a sequence of integers spaced by a given time interval

  ![Interval](http://reactivex.io/documentation/operators/images/interval.c.png)  The Interval operator returns an Observable that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between emissions. 

  #### See Also

 * [Range](range)
* [Repeat](repeat)
* [Timer](timer)
* [Introduction to Rx: Interval](http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableInterval)
* [101 Rx Samples: Observing the Passing of Time](http://rxwiki.wikidot.com/101samples#toc15)
* [101 Rx Samples: Interval — Simple](http://rxwiki.wikidot.com/101samples#toc28)
* [ad-hockery: Simple Background Polling with RxJava](http://blog.freeside.co/2015/01/29/simple-background-polling-with-rxjava/)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `interval`

     ![interval](http://reactivex.io/documentation/operators/images/interval.png)  RxGroovy implements this operator as `interval`. It accepts as its parameters a span of time to wait between emissions and the `TimeUnit` in which this span is measured. 

 * Javadoc: [`interval(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`interval(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20java.util.concurrent.TimeUnit%20rx.Scheduler))
   ![timer](http://reactivex.io/documentation/operators/images/timer.p.png)  There is also a version of `interval` that returns an Observable that emits a single zero after a specified delay, and then emits incrementally increasing numbers periodically thereafter on a specified periodicity. This version of `interval` was called [`timer`](timer) in RxGroovy 1.0.0, but that method has since been deprecated in favor of the one named `interval` with the same behavior. 

 * Javadoc: [`interval(long,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`interval(long,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   `interval` operates by default on the `computation` [Scheduler](../scheduler). There are also variants that allow you to set the Scheduler by passing one in as a parameter. 

      ###  RxJava 1․x `interval`

     ![interval](http://reactivex.io/documentation/operators/images/interval.png)  RxJava implements this operator as `interval`. It accepts as its parameters a span of time to wait between emissions and the `TimeUnit` in which this span is measured. 

 * Javadoc: [`interval(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`interval(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20java.util.concurrent.TimeUnit%20rx.Scheduler))
   ![timer](http://reactivex.io/documentation/operators/images/timer.p.png)  There is also a version of `interval` that returns an Observable that emits a single zero after a specified delay, and then emits incrementally increasing numbers periodically thereafter on a specified periodicity. This version of `interval` was called [`timer`](timer) in RxJava 1.0.0, but that method has since been deprecated in favor of the one named `interval` with the same behavior. 

 * Javadoc: [`interval(long,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`interval(long,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   `interval` operates by default on the `computation` [Scheduler](../scheduler). There are also variants that allow you to set the Scheduler by passing one in as a parameter. 

      ###  RxJS `interval`

     ![interval](http://reactivex.io/documentation/operators/images/interval.png)  RxJS implements this operator as `interval`. It accepts as its parameter the number of milliseconds to wait between emissions. 


 `interval` operates by default on the `timeout` [Scheduler](../scheduler), or you can optionally pass in a different Scheduler as a second parameter, and `interval` will operate on that Scheduler instead. 

 #### Sample Code

 
```
var source = Rx.Observable
    .interval(500 /* ms */)
    .timeInterval()
    .take(3);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```


```
Next: {value: 0, interval: 500}
Next: {value: 1, interval: 500}
Next: {value: 2, interval: 500}
Completed
```
  `interval` is found in the following distributions: 

 * `rx.lite.js`
* `rx.lite.compat.js`
* `rx.timejs` (requires `rx.js` or `rx.compat.js`)

        ###  RxPHP `interval`

       RxPHP implements this operator as `interval`. 

  Returns an Observable that emits an infinite sequence of ascending integers starting at 0, with a constant interval of time of your choosing between emissions. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/interval/interval.php

\Rx\Observable::interval(1000)
    ->take(5)
    ->subscribe($createStdoutObserver());
```
  
```
Next value: 0
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/interval.html>

Repeat
======

 
> create an Observable that emits a particular item multiple times

  ![Repeat](http://reactivex.io/documentation/operators/images/repeat.c.png)  The Repeat operator emits an item repeatedly. Some implementations of this operator allow you to repeat a *sequence* of items, and some permit you to limit the number of repetitions. 

  #### See Also

 * [Interval](interval)
* [Range](range)
* [Introduction to Rx: Repeat](http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#Repeat)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `doWhile repeat repeatWhen whileDo`

     ![repeat](http://reactivex.io/documentation/operators/images/repeat.o.png)  RxGroovy implements this operator as `repeat`. It does not initiate an Observable, but operates on an Observable in such a way that it repeats the sequence emitted by the source Observable as its own sequence, either infinitely, or in the case of `repeat(*n*)`, *n* times. 


 `repeat` operates by default on the `trampoline` [Scheduler](../scheduler). There is also a variant that allows you to set the Scheduler by passing one in as a parameter. 

 * Javadoc: [`repeat()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat())
* Javadoc: [`repeat(long)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat(long))
* Javadoc: [`repeat(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat(rx.Scheduler))
* Javadoc: [`repeat(long,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat(long,%20rx.Scheduler))
   ![repeatWhen](http://reactivex.io/documentation/operators/images/repeatWhen.f.png)  There is also an operator called `repeatWhen`. Rather than buffering and replaying the sequence from the source Observable, it *resubscribes* to and mirrors the source Observable, but only conditionally. 


 It decides whether to resubscribe and remirror the source Observable by passing that Observable’s termination notifications (error or completed) to a notification handler as `void` emissions. This notification handler acts as an Observable operator, taking an Observable that emits these `void` notifications as input, and returning an Observable that emits `void` items (meaning, resubscribe and mirror the source Observable) or terminates (meaning, terminate the sequence emitted by `repeatWhen`). 


 `repeatWhen` operates by default on the `trampoline` [Scheduler](../scheduler). There is also a variant that allows you to set the Scheduler by passing one in as a parameter. 

 * Javadoc: [`repeatWhen(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeatWhen(rx.functions.Func1))
* Javadoc: [`repeatWhen(Func1,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeatWhen(rx.functions.Func1,%20rx.Scheduler))
   ![doWhile](http://reactivex.io/documentation/operators/images/doWhile.png)  In RxGroovy, `doWhile` is not part of the standard set of operators, but is part of the optional `rxjava-computation-expressions` package. `doWhile` checks a condition after each repetition of the source sequence, and only repeats it if that condition is true. 

   ![whileDo](http://reactivex.io/documentation/operators/images/whileDo.png)  In RxGroovy, `whileDo` is not part of the standard set of operators, but is part of the optional `rxjava-computation-expressions` package. `whileDo` checks a condition before each repetition of the source sequence, and only repeats it if that condition is true. 

       ###  RxJava 1․x `doWhile repeat repeatWhen whileDo`

     ![repeat](http://reactivex.io/documentation/operators/images/repeat.o.png)  RxJava implements this operator as `repeat`. It does not initiate an Observable, but operates on an Observable in such a way that it repeats the sequence emitted by the source Observable as its own sequence, either infinitely, or in the case of `repeat(*n*)`, *n* times. 


 `repeat` operates by default on the `trampoline` [Scheduler](../scheduler). There is also a variant that allows you to set the Scheduler by passing one in as a parameter. 

 * Javadoc: [`repeat()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat())
* Javadoc: [`repeat(long)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat(long))
* Javadoc: [`repeat(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat(rx.Scheduler))
* Javadoc: [`repeat(long,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeat(long,%20rx.Scheduler))
   ![repeatWhen](http://reactivex.io/documentation/operators/images/repeatWhen.f.png)  There is also an operator called `repeatWhen`. Rather than buffering and replaying the sequence from the source Observable, it *resubscribes* to and mirrors the source Observable, but only conditionally. 


 It decides whether to resubscribe and remirror the source Observable by passing that Observable’s termination notifications (error or completed) to a notification handler as `void` emissions. This notification handler acts as an Observable operator, taking an Observable that emits these `void` notifications as input, and returning an Observable that emits `void` items (meaning, resubscribe and mirror the source Observable) or terminates (meaning, terminate the sequence emitted by `repeatWhen`). 


 `repeatWhen` operates by default on the `trampoline` [Scheduler](../scheduler). There is also a variant that allows you to set the Scheduler by passing one in as a parameter. 

 * Javadoc: [`repeatWhen(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeatWhen(rx.functions.Func1))
* Javadoc: [`repeatWhen(Func1,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#repeatWhen(rx.functions.Func1,%20rx.Scheduler))
   ![doWhile](http://reactivex.io/documentation/operators/images/doWhile.png)  In RxJava, `doWhile` is not part of the standard set of operators, but is part of the optional `rxjava-computation-expressions` package. `doWhile` checks a condition after each repetition of the source sequence, and only repeats it if that condition is true. 

   ![whileDo](http://reactivex.io/documentation/operators/images/whileDo.png)  In RxJava, `whileDo` is not part of the standard set of operators, but is part of the optional `rxjava-computation-expressions` package. `whileDo` checks a condition before each repetition of the source sequence, and only repeats it if that condition is true. 

       ###  RxJS `doWhile repeat while`

     ![repeat](http://reactivex.io/documentation/operators/images/repeat.png)  RxJS implements this operator as `repeat`. It accepts as its parameter the item to repeat, and optionally two other parameters: the number of times you want the item to repeat, and the [Scheduler](../scheduler) on which you want to perform this operation (it uses the `immediate` Scheduler by default). 

 #### Sample Code

 
```
var source = Rx.Observable.repeat(42, 3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 42
Next: 42
Next: 42
Completed
```
  `repeat` is found in the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![doWile](http://reactivex.io/documentation/operators/images/doWhile.png)  RxJS also implements the `doWhile` operator. It repeats the source Observable’s sequence of emissions only so long as a condition you specify remains true. 

 
```
var i = 0;

var source = Rx.Observable.return(42).doWhile(
    function (x) { return ++i < 2; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Next: 42
Completed
```
 `doWhile` is found in each of the following distributions. 


* `rx.all.js`
* `rx.all.compat.js`
* `rx.experimental.js`

 It requires one of the following distributions:

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![while](http://reactivex.io/documentation/operators/images/while.png)  RxJS also implements the `while` operator. It repeats the source Observable’s sequence of emissions only if a condition you specify is true. 

 
```
var i = 0;

// Repeat until condition no longer holds
var source = Rx.Observable.while(
    function () { return i++ < 3 },
    Rx.Observable.return(42)
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Next: 42
Next: 42
Completed
```
 `while` is found in the `rx.experimental.js` distribution. It requires one of the following distributions:

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `repeat repeatWhen`

       RxPHP implements this operator as `repeat`. 

  Generates an observable sequence that repeats the given element the specified number of times. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/repeat/repeat.php

$source = \Rx\Observable::range(1, 3)
    ->repeat(3);

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 1
Next value: 2
Next value: 3
Next value: 1
Next value: 2
Next value: 3
Next value: 1
Next value: 2
Next value: 3
Complete!
```
      RxPHP also has an operator `repeatWhen`. 

  Returns an Observable that emits the same values as the source Observable with the exception of an onCompleted. An onCompleted notification from the source will result in the emission of a count item to the Observable provided as an argument to the notificationHandler function. If that Observable calls onComplete or onError then repeatWhen will call onCompleted or onError on the child subscription. Otherwise, this Observable will resubscribe to the source observable. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/repeat/repeatWhen.php

$source = Rx\Observable::of(42)
    ->repeatWhen(function (\Rx\Observable $notifications) {
        return $notifications
            ->scan(function ($acc, $x) {
                return $acc + $x;
            }, 0)
            ->delay(1000)
            ->doOnNext(function () {
                echo "1 second delay", PHP_EOL;
            })
            ->takeWhile(function ($count) {
                return $count < 2;
            });
    });

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 42
1 second delay
Next value: 42
1 second delay
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/repeat.html>

Replay
======

 
> ensure that all observers see the same sequence of emitted items, even if they subscribe after the Observable has begun emitting items

  ![Replay](http://reactivex.io/documentation/operators/images/replay.c.png)  A connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when the Connect operator is applied to it. In this way you can prompt an Observable to begin emitting items at a time of your choosing. 


 If you apply the Replay operator to an Observable before you convert it into a connectable Observable, the resulting connectable Observable will always emit the same complete sequence to any future observers, even those observers that subscribe after the connectable Observable has begun to emit items to other subscribed observers. 

  #### See Also

 * [Connect](connect)
* [Publish](publish)
* [RefCount](refcount)
* [Introduction to Rx: Replay](http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#Replay)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `replay cache`

     ![replay](http://reactivex.io/documentation/operators/images/replay.png)  In RxGroovy there is a variety of the `replay` operator that returns a connectable Observable. You must [Publish](publish) this connectable Observable before observers can subscribe to it, and then [Connect](connect) to it in order to observe its emissions. 


 Variants of this variety of the `replay` operator permit you to set a maximum buffer size to limit the number of items `replay` will buffer and replay to subsequent observers, and/or to establish a moving time window that defines when emitted items become too old to buffer and replay. 

 * Javadoc: [`replay()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay())
* Javadoc: [`replay(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.Scheduler))
* Javadoc: [`replay(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int))
* Javadoc: [`replay(int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int,%20rx.Scheduler))
* Javadoc: [`replay(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
* Javadoc: [`replay(int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![replay](http://reactivex.io/documentation/operators/images/replay.f.png)  There is also a variety of `replay` that returns an ordinary Observable. These variants take as a parameter a transformative function; this function accepts an item emitted by the source Observable as its parameter, and returns an item to be emitted by the resulting Observable. So really, this operator does not replay the source Observable but instead replays the source Observable *as transformed* by this function. 


 Variants of this variety of the `replay` operator permit you to set a maximum buffer size to limit the number of items `replay` will buffer and replay to subsequent observers, and/or to establish a moving time window that defines when emitted items become too old to buffer and replay. 

 * Javadoc: [`replay(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1))
* Javadoc: [`replay(Func1,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20rx.Scheduler))
* Javadoc: [`replay(Func1,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int))
* Javadoc: [`replay(Func1,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int,%20rx.Scheduler))
* Javadoc: [`replay(Func1,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(Func1,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
* Javadoc: [`replay(Func1,int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(Func1,int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJava 1․x `cache replay`

     ![replay](http://reactivex.io/documentation/operators/images/replay.png)  In RxJava there is a variety of the `replay` operator that returns a connectable Observable. You must [Publish](publish) this connectable Observable before observers can subscribe to it, and then [Connect](connect) to it in order to observe its emissions. 


 Variants of this variety of the `replay` operator permit you to set a maximum buffer size to limit the number of items `replay` will buffer and replay to subsequent observers, and/or to establish a moving time window that defines when emitted items become too old to buffer and replay. 

 * Javadoc: [`replay()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay())
* Javadoc: [`replay(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.Scheduler))
* Javadoc: [`replay(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int))
* Javadoc: [`replay(int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int,%20rx.Scheduler))
* Javadoc: [`replay(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
* Javadoc: [`replay(int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![replay](http://reactivex.io/documentation/operators/images/replay.f.png)  There is also a variety of `replay` that returns an ordinary Observable. These variants take as a parameter a transformative function; this function accepts an item emitted by the source Observable as its parameter, and returns an item to be emitted by the resulting Observable. So really, this operator does not replay the source Observable but instead replays the source Observable *as transformed* by this function. 


 Variants of this variety of the `replay` operator permit you to set a maximum buffer size to limit the number of items `replay` will buffer and replay to subsequent observers, and/or to establish a moving time window that defines when emitted items become too old to buffer and replay. 

 * Javadoc: [`replay(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1))
* Javadoc: [`replay(Func1,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20rx.Scheduler))
* Javadoc: [`replay(Func1,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int))
* Javadoc: [`replay(Func1,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int,%20rx.Scheduler))
* Javadoc: [`replay(Func1,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(Func1,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
* Javadoc: [`replay(Func1,int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`replay(Func1,int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(rx.functions.Func1,%20int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJS `replay shareReplay`

     ![replay](http://reactivex.io/documentation/operators/images/replay.fnts.png)  In RxJs the `replay` operator takes four optional parameters and returns an ordinary Observable: 

  `selector`
a transforming function that takes an item emitted by the source Observable as its parameter and returns an item to be emitted by the resulting Observable `bufferSize`
the maximum number of items to buffer and replay to subsequent observers `window`
the age, in milliseconds, at which items in this buffer may be discarded without being emitted to subsequent observers `scheduler`
the [Scheduler](../scheduler) on which this operator will operate  #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(2)
    .do(function (x) {
        console.log('Side effect');
    });

var published = source
    .replay(function (x) {
        return x.take(2).repeat(2);
    }, 3);

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Side effect
Next: SourceA0
Side effect
Next: SourceB0
Side effect
Next: SourceA1
Next: SourceA0
Next: SourceA1
Completed
Side effect
Next: SourceB1
Next: SourceB0
Next: SourceB1
Completed
```
    There is also a `shareReplay` operator, which keeps track of the number of observers, and disconnects from the source Observable when that number drops to zero. `shareReplay` takes three optional parameters and returns an ordinary Observable: 

  `bufferSize`
the maximum number of items to buffer and replay to subsequent observers `window`
the age, in milliseconds, at which items in this buffer may be discarded without being emitted to subsequent observers `scheduler`
the [Scheduler](../scheduler) on which this operator will operate  #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(4)
    .doAction(function (x) {
        console.log('Side effect');
    });

var published = source
    .shareReplay(3);

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

// Creating a third subscription after the previous two subscriptions have
// completed. Notice that no side effects result from this subscription,
// because the notifications are cached and replayed.
Rx.Observable
    .return(true)
    .delay(6000)
    .flatMap(published)
    .subscribe(createObserver('SourceC'));

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Side effect
Next: SourceA0
Next: SourceB0
Side effect
Next: SourceA1
Next: SourceB1
Side effect
Next: SourceA2
Next: SourceB2
Side effect
Next: SourceA3
Next: SourceB3
Completed
Completed
Next: SourceC1
Next: SourceC2
Next: SourceC3
Completed
```
  `replay` and `shareReplay` are found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.binding.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `replay shareReplay`

       RxPHP implements this operator as `replay`. 

  Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. This operator is a specialization of Multicast using a ReplaySubject. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/replay/replay.php

$interval = \Rx\Observable::interval(1000);

$source = $interval
    ->take(2)
    ->doOnNext(function ($x) {
        echo $x, ' something', PHP_EOL;
        echo 'Side effect', PHP_EOL;
    });

$published = $source
    ->replay(function (\Rx\Observable $x) {
        return $x->take(2)->repeat(2);
    }, 3);

$published->subscribe($createStdoutObserver('SourceA '));
$published->subscribe($createStdoutObserver('SourceB '));
```
  
```
0 something
Side effect
0 something
Side effect
SourceA Next value: 0
SourceB Next value: 0
SourceA Next value: 0
SourceB Next value: 0
SourceA Next value: 0
SourceB Next value: 0
SourceA Next value: 0
SourceA Complete!
SourceB Next value: 0
SourceB Complete!
1 something
Side effect
1 something
Side effect
```
      RxPHP also has an operator `shareReplay`. 

  Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/share/shareReplay.php

$interval = Rx\Observable::interval(1000);

$source = $interval
    ->take(4)
    ->doOnNext(function ($x) {
        echo 'Side effect', PHP_EOL;
    });

$published = $source
    ->shareReplay(3);

$published->subscribe($createStdoutObserver('SourceA '));
$published->subscribe($createStdoutObserver('SourceB '));

Rx\Observable
    ::of(true)
    ->concatMapTo(\Rx\Observable::timer(6000))
    ->flatMap(function () use ($published) {
        return $published;
    })
    ->subscribe($createStdoutObserver('SourceC '));
```
  
```
Side effect
SourceA Next value: 0
SourceB Next value: 0
Side effect
SourceA Next value: 1
SourceB Next value: 1
Side effect
SourceA Next value: 2
SourceB Next value: 2
Side effect
SourceA Next value: 3
SourceB Next value: 3
SourceA Complete!
SourceB Complete!
SourceC Next value: 1
SourceC Next value: 2
SourceC Next value: 3
SourceC Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/replay.html>

Buffer
======

 
> periodically gather items emitted by an Observable into bundles and emit these bundles rather than emitting the items one at a time

  ![Buffer](http://reactivex.io/documentation/operators/images/Buffer.png)  The Buffer operator transforms an Observable that emits items into an Observable that emits buffered collections of those items. There are a number of variants in the various language-specific implementations of Buffer that differ in how they choose which items go in which buffers. 


 Note that if the source Observable issues an `onError` notification, Buffer will pass on this notification immediately without first emitting the buffer it is in the process of assembling, even if that buffer contains items that were emitted by the source Observable before it issued the error notification. 

   The [Window](window) operator is similar to Buffer but collects items into separate Observables rather than into data structures before reemitting them. 

 #### See Also

 * [Window](window)
* [Introduction to Rx: Buffer](http://www.introtorx.com/Content/v1.0.10621.0/13_TimeShiftedSequences.html#Buffer)
* [Introduction to Rx: Buffer revisited](http://www.introtorx.com/Content/v1.0.10621.0/17_SequencesOfCoincidence.html#BufferRevisted)
* [101 Rx Samples: Buffer — Simple](http://rxwiki.wikidot.com/101samples#toc26)

 Language-Specific Information
-----------------------------

    ###  RxCpp `buffer pairwise`

     RxCpp implements two variants of Buffer: 

 #### `buffer(count)`

  ![buffer(count)](http://reactivex.io/documentation/operators/images/buffer3.png)  `buffer(count)` emits non-overlapping buffers in the form of `vector`s, each of which contains at most `count` items from the source Observable (the final emitted `vector` may have fewer than `count` items).

   #### `buffer(count, skip)`

  ![buffer(count,skip)](http://reactivex.io/documentation/operators/images/buffer4.png)  `buffer(count, skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as `vector`s. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

        ###  RxGroovy `buffer`

     In RxGroovy there are several variants of Buffer: 

 #### `buffer(count)`

  ![buffer(count)](http://reactivex.io/documentation/operators/images/buffer3.png)  `buffer(count)` emits non-overlapping buffers in the form of `List`s, each of which contains at most `count` items from the source Observable (the final emitted `List` may have fewer than `count` items).

 * Javadoc: [`buffer(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(int))
  #### `buffer(count, skip)`

  ![buffer(count,skip)](http://reactivex.io/documentation/operators/images/buffer4.png)  `buffer(count, skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as `List`s. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

 * Javadoc: [`buffer(int,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(int,%20int))
  #### `buffer(bufferClosingSelector)`

  ![buffer(bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer1.png)  When it subscribes to the source Observable, `buffer(bufferClosingSelector)` begins to collect its emissions into a `List`, and it also calls `bufferClosingSelector` to generate a second Observable. When this second Observable emits an `TClosing` object, `buffer` emits the current `List` and repeats this process: beginning a new `List` and calling `bufferClosingSelector` to create a new Observable to monitor. It will do this until the source Observable terminates.

 * Javadoc: [`buffer(Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.functions.Func0))
  #### 
`buffer(boundary`[`, initialCapacity`]`)`

  ![buffer(boundary)](http://reactivex.io/documentation/operators/images/buffer8.png)  `buffer(boundary)` monitors an Observable, `boundary`. Each time that Observable emits an item, it creates a new `List` to begin collecting items emitted by the source Observable and emits the previous `List`.

 * Javadoc: [`buffer(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.Observable))
* Javadoc: [`buffer(Observable,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.Observable,%20int))
  #### `buffer(bufferOpenings, bufferClosingSelector)`

  ![buffer(bufferOpenings,bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer2.png)  `buffer(bufferOpenings, bufferClosingSelector)` monitors an Observable, `bufferOpenings`, that emits `BufferOpening` objects. Each time it observes such an emitted item, it creates a new `List` to begin collecting items emitted by the source Observable and it passes the `bufferOpenings` Observable into the `closingSelector` function. That function returns an Observable. `buffer` monitors that Observable and when it detects an emitted item from it, it closes the `List` and emits it as its own emission.

 * Javadoc: [`buffer(Observable,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.Observable,%20rx.functions.Func1))
  #### 
`buffer(timespan, unit`[`, scheduler`]`)`

  ![buffer(timespan,unit)](http://reactivex.io/documentation/operators/images/buffer5.png)  `buffer(timespan, unit)` emits a new `List` of items periodically, every `timespan` amount of time, containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first bundle, since the subscription to the source Observable. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` Scheduler.

 * Javadoc: [`buffer(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`buffer(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
  #### 
`buffer(timespan, unit, count`[`, scheduler`]`)`

  ![buffer(timespan,unit,count)](http://reactivex.io/documentation/operators/images/buffer6.png)  `buffer(timespan, unit, count)` emits a new `List` of items for every `count` items emitted by the source Observable, or, if `timespan` has elapsed since its last bundle emission, it emits a bundle of however many items the source Observable has emitted in that span, even if this is fewer than `count`. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

 * Javadoc: [`buffer(long,TimeUnit,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit,%20int))
* Javadoc: [`buffer(long,TimeUnit,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit,%20int,%20rx.Scheduler))
  #### 
`buffer(timespan, timeshift, unit`[`, scheduler`]`)`

  ![buffer(timespan,timeshift,unit)](http://reactivex.io/documentation/operators/images/buffer7.png)  `buffer(timespan, timeshift, unit)` creates a new `List` of items every `timeshift` period of time, and fills this bundle with every item emitted by the source Observable from that time until `timespan` time has passed since the bundle’s creation, before emitting this `List` as its own emission. If `timespan` is longer than `timeshift`, the emitted bundles will represent time periods that overlap and so they may contain duplicate items. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

 * Javadoc: [`buffer(long,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`buffer(long,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   You can use the Buffer operator to implement backpressure (that is, to cope with an Observable that may produce items too quickly for its observer to consume). 

  ![Buffer as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.buffer2.png)  Buffer can reduce a sequence of many items to a sequence of fewer buffers-of-items, making them more manageable. You could, for example, close and emit a buffer of items from a bursty Observable periodically, at a regular interval of time. 

 #### Sample Code

 
```
Observable<List<Integer>> burstyBuffered = bursty.buffer(500, TimeUnit.MILLISECONDS);
```
    ![Buffer as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.buffer1.png)  Or you could get fancy, and collect items in buffers during the bursty periods and emit them at the end of each burst, by using the [Debounce](debounce) operator to emit a buffer closing indicator to the buffer operator. 

 #### Sample Code

 
```
// we have to multicast the original bursty Observable so we can use it
// both as our source and as the source for our buffer closing selector:
Observable<Integer> burstyMulticast = bursty.publish().refCount();
// burstyDebounced will be our buffer closing selector:
Observable<Integer> burstyDebounced = burstyMulticast.debounce(10, TimeUnit.MILLISECONDS);
// and this, finally, is the Observable of buffers we're interested in:
Observable<List<Integer>> burstyBuffered = burstyMulticast.buffer(burstyDebounced);
```
        ###  RxJava 1․x `buffer`

     In RxJava there are several variants of Buffer: 

 #### `buffer(count)`

  ![buffer(count)](http://reactivex.io/documentation/operators/images/buffer3.png)  `buffer(count)` emits non-overlapping buffers in the form of `List`s, each of which contains at most `count` items from the source Observable (the final emitted `List` may have fewer than `count` items).

 * Javadoc: [`buffer(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(int))
  #### `buffer(count, skip)`

  ![buffer(count,skip)](http://reactivex.io/documentation/operators/images/buffer4.png)  `buffer(count, skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as `List`s. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

 * Javadoc: [`buffer(int,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(int,%20int))
  #### `buffer(bufferClosingSelector)`

  ![buffer(bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer1.png)  When it subscribes to the source Observable, `buffer(bufferClosingSelector)` begins to collect its emissions into a `List`, and it also calls `bufferClosingSelector` to generate a second Observable. When this second Observable emits an `TClosing` object, `buffer` emits the current `List` and repeats this process: beginning a new `List` and calling `bufferClosingSelector` to create a new Observable to monitor. It will do this until the source Observable terminates.

 * Javadoc: [`buffer(Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.functions.Func0))
  #### `buffer(boundary)`

  ![buffer(boundary)](http://reactivex.io/documentation/operators/images/buffer8.png)  `buffer(boundary)` monitors an Observable, `boundary`. Each time that Observable emits an item, it creates a new `List` to begin collecting items emitted by the source Observable and emits the previous `List`.

 * Javadoc: [`buffer(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.Observable))
* Javadoc: [`buffer(Observable,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.Observable,%20int))
  #### `buffer(bufferOpenings, bufferClosingSelector)`

  ![buffer(bufferOpenings,bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer2.png)  `buffer(bufferOpenings, bufferClosingSelector)` monitors an Observable, `bufferOpenings`, that emits `BufferOpening` objects. Each time it observes such an emitted item, it creates a new `List` to begin collecting items emitted by the source Observable and it passes the `bufferOpenings` Observable into the `closingSelector` function. That function returns an Observable. `buffer` monitors that Observable and when it detects an emitted item from it, it closes the `List` and emits it as its own emission.

 * Javadoc: [`buffer(Observable,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(rx.Observable,%20rx.functions.Func1))
  #### 
`buffer(timespan, unit`[`, scheduler`]`)`

  ![buffer(timespan,unit)](http://reactivex.io/documentation/operators/images/buffer5.png)  `buffer(timespan, unit)` emits a new `List` of items periodically, every `timespan` amount of time, containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first bundle, since the subscription to the source Observable. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

 * Javadoc: [`buffer(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`buffer(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
  #### 
`buffer(timespan, unit, count`[`, scheduler`]`)`

  ![buffer(timespan,unit,count)](http://reactivex.io/documentation/operators/images/buffer6.png)  `buffer(timespan, unit, count)` emits a new `List` of items for every `count` items emitted by the source Observable, or, if `timespan` has elapsed since its last bundle emission, it emits a bundle of however many items the source Observable has emitted in that span, even if this is fewer than `count`. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

 * Javadoc: [`buffer(long,TimeUnit,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit,%20int))
* Javadoc: [`buffer(long,TimeUnit,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20java.util.concurrent.TimeUnit,%20int,%20rx.Scheduler))
  #### 
`buffer(timespan, timeshift, unit`[`, scheduler`]`)`

  ![buffer(timespan,timeshift,unit)](http://reactivex.io/documentation/operators/images/buffer7.png)  `buffer(timespan, timeshift, unit)` creates a new `List` of items every `timeshift` period of time, and fills this bundle with every item emitted by the source Observable from that time until `timespan` time has passed since the bundle’s creation, before emitting this `List` as its own emission. If `timespan` is longer than `timeshift`, the emitted bundles will represent time periods that overlap and so they may contain duplicate items. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

 * Javadoc: [`buffer(long,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`buffer(long,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#buffer(long,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   You can use the Buffer operator to implement backpressure (that is, to cope with an Observable that may produce items too quickly for its observer to consume). 

  ![Buffer as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.buffer2.png)  Buffer can reduce a sequence of many items to a sequence of fewer buffers-of-items, making them more manageable. You could, for example, close and emit a buffer of items from a bursty Observable periodically, at a regular interval of time. 

 #### Sample Code

 
```
Observable<List<Integer>> burstyBuffered = bursty.buffer(500, TimeUnit.MILLISECONDS);
```
    ![Buffer as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.buffer1.png)  Or you could get fancy, and collect items in buffers during the bursty periods and emit them at the end of each burst, by using the [Debounce](debounce) operator to emit a buffer closing indicator to the buffer operator. 

 #### Sample Code

 
```
// we have to multicast the original bursty Observable so we can use it
// both as our source and as the source for our buffer closing selector:
Observable<Integer> burstyMulticast = bursty.publish().refCount();
// burstyDebounced will be our buffer closing selector:
Observable<Integer> burstyDebounced = burstyMulticast.debounce(10, TimeUnit.MILLISECONDS);
// and this, finally, is the Observable of buffers we're interested in:
Observable<List<Integer>> burstyBuffered = burstyMulticast.buffer(burstyDebounced);
```
   #### See Also

 * [DebouncedBuffer With RxJava by Gopal Kaushik](http://blog.kaush.co/2015/01/05/debouncedbuffer-with-rxjava/)
* [DebounceBuffer: Use publish(), debounce() and buffer() together to capture bursts of events. by Ben Christensen](https://gist.github.com/benjchristensen/e4524a308456f3c21c0b#file-debouncebufferpublish-java)

      ###  RxJS `buffer bufferWithCount bufferWithTime bufferWithTimeOrCount`

     RxJS has four Buffer operators — `buffer`, `bufferWithCount`, `bufferWithTime`, and `bufferWithTimeOrCount` — each of which has variants that have different ways of governing which source Observable items are emitted as part of which buffers. 

 #### `buffer(bufferBoundaries)`

  ![buffer(bufferBoundaries)](http://reactivex.io/documentation/operators/images/buffer8.png)  `buffer(bufferBoundaries)` monitors an Observable, `bufferBoundaries`. Each time that Observable emits an item, it creates a new collection to begin collecting items emitted by the source Observable and emits the previous collection.

   #### `buffer(bufferClosingSelector)`

  ![buffer(bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer1.png)  When it subscribes to the source Observable, `buffer(bufferClosingSelector)` begins to collect its emissions into a collection, and it also calls `bufferClosingSelector` to generate a second Observable. When this second Observable emits an item, `buffer` emits the current collection and repeats this process: beginning a new collection and calling `bufferClosingSelector` to create a new Observable to monitor. It will do this until the source Observable terminates.

   #### `buffer(bufferOpenings,bufferClosingSelector)`

  ![buffer(bufferOpenings,bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer2.png)  `buffer(bufferOpenings, bufferClosingSelector)` monitors an Observable, `bufferOpenings`, that emits `BufferOpening` objects. Each time it observes such an emitted item, it creates a new collection to begin collecting items emitted by the source Observable and it passes the `bufferOpenings` Observable into the `bufferClosingSelector` function. That function returns an Observable. `buffer` monitors that Observable and when it detects an emitted item from it, it emits the current collection and begins a new one.

    `buffer` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.coincidence.js`

  `buffer` requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

 #### `bufferWithCount(count)`

  ![bufferWithCount(count)](http://reactivex.io/documentation/operators/images/bufferWithCount3.png)  `bufferWithCount(count)` emits non-overlapping buffers, each of which contains at most `count` items from the source Observable (the final emitted buffer may contain fewer than `count` items).

   #### `bufferWithCount(count, skip)`

  ![bufferWithCount(count,skip)](http://reactivex.io/documentation/operators/images/bufferWithCount4.png)  `bufferWithCount(count, skip)` creates a new buffer starting with the first emitted item from the source Observable, and a new one for every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones, emitting each buffer when it is complete. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

    `bufferWithCount` is found in each of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.lite.extras.js`

 #### `bufferWithTime(timeSpan)`

  ![bufferWithTime(timeSpan)](http://reactivex.io/documentation/operators/images/bufferWithTime5.png)  `bufferWithTime(timeSpan)` emits a new collection of items periodically, every `timeSpan` milliseconds, containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first bundle, since the subscription to the source Observable. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `timeout` scheduler.

   #### `bufferWithTime(timeSpan, timeShift)`

  ![bufferWithTime(timeSpan,timeShift)](http://reactivex.io/documentation/operators/images/bufferWithTime7.png)  `bufferWithTime(timeSpan, timeShift)` creates a new collection of items every `timeShift` milliseconds, and fills this bundle with every item emitted by the source Observable from that time until `timeSpan` milliseconds has passed since the collection’s creation, before emitting this collection as its own emission. If `timeSpan` is longer than `timeShift`, the emitted bundles will represent time periods that overlap and so they may contain duplicate items. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `timeout` scheduler.

   #### `bufferWithTimeOrCount(timeSpan, count)`

  ![bufferWithTimeOrCount(timeSpan,count)](http://reactivex.io/documentation/operators/images/bufferWithTimeOrCount6.png)  `bufferWithTimeOrCount(timeSpan, count)` emits a new collection of items for every `count` items emitted by the source Observable, or, if `timeSpan` milliseconds have elapsed since its last collection emission, it emits a collection of however many items the source Observable has emitted in that span, even if this is fewer than `count`. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `timeout` scheduler.

    `bufferWithTime` and `bufferWithTimeOrCount` are found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js`

  `bufferWithTime` and `bufferWithTimeOrCount` require one of the following distributions: 

 * `rx.time.js` requires `rx.js` or `rx.compat.js`
* otherwise: `rx.lite.js` or `rx.lite.compat.js`

      ###  RxKotlin `buffer`

     In RxKotlin there are several variants of Buffer: 

 #### `buffer(count)`

  ![buffer(count)](http://reactivex.io/documentation/operators/images/buffer3.png)  `buffer(count)` emits non-overlapping buffers in the form of `List`s, each of which contains at most `count` items from the source Observable (the final emitted `List` may have fewer than `count` items).

   #### `buffer(count, skip)`

  ![buffer(count,skip)](http://reactivex.io/documentation/operators/images/buffer4.png)  `buffer(count, skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as `List`s. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

   #### `buffer(bufferClosingSelector)`

  ![buffer(bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer1.png)  When it subscribes to the source Observable, `buffer(bufferClosingSelector)` begins to collect its emissions into a `List`, and it also calls `bufferClosingSelector` to generate a second Observable. When this second Observable emits an `TClosing` object, `buffer` emits the current `List` and repeats this process: beginning a new `List` and calling `bufferClosingSelector` to create a new Observable to monitor. It will do this until the source Observable terminates.

   #### `buffer(boundary)`

  ![buffer(boundary)](http://reactivex.io/documentation/operators/images/buffer8.png)  `buffer(boundary)` monitors an Observable, `boundary`. Each time that Observable emits an item, it creates a new `List` to begin collecting items emitted by the source Observable and emits the previous `List`.

   #### `buffer(bufferOpenings, bufferClosingSelector)`

  ![buffer(bufferOpenings,bufferClosingSelector)](http://reactivex.io/documentation/operators/images/buffer2.png)  `buffer(bufferOpenings, bufferClosingSelector)` monitors an Observable, `bufferOpenings`, that emits `BufferOpening` objects. Each time it observes such an emitted item, it creates a new `List` to begin collecting items emitted by the source Observable and it passes the `bufferOpenings` Observable into the `closingSelector` function. That function returns an Observable. `buffer` monitors that Observable and when it detects an emitted item from it, it closes the `List` and emits it as its own emission.

   #### 
`buffer(timespan, unit`[`, scheduler`]`)`

  ![buffer(timespan,unit)](http://reactivex.io/documentation/operators/images/buffer5.png)  `buffer(timespan, unit)` emits a new `List` of items periodically, every `timespan` amount of time, containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first bundle, since the subscription to the source Observable. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

   #### 
`buffer(timespan, unit, count`[`, scheduler`]`)`

  ![buffer(timespan,unit,count)](http://reactivex.io/documentation/operators/images/buffer6.png)  `buffer(timespan, unit, count)` emits a new `List` of items for every `count` items emitted by the source Observable, or, if `timespan` has elapsed since its last bundle emission, it emits a bundle of however many items the source Observable has emitted in that span, even if this is fewer than `count`. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

   #### 
`buffer(timespan, timeshift, unit`[`, scheduler`]`)`

  ![buffer(timespan,timeshift,unit)](http://reactivex.io/documentation/operators/images/buffer7.png)  `buffer(timespan, timeshift, unit)` creates a new `List` of items every `timeshift` period of time, and fills this bundle with every item emitted by the source Observable from that time until `timespan` time has passed since the bundle’s creation, before emitting this `List` as its own emission. If `timespan` is longer than `timeshift`, the emitted bundles will represent time periods that overlap and so they may contain duplicate items. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan; by default this variant uses the `computation` scheduler.

        ###  RxNET `Buffer`

     In Rx.NET there are several variants of Buffer. For each variety you can either pass in the source Observable as the first parameter, or you can call it as an instance method of the source Observable (in which case you can omit that parameter): 

 #### `Buffer(count)`

  ![Buffer(count)](http://reactivex.io/documentation/operators/images/Buffer3.net.png)  `Buffer(count)` emits non-overlapping buffers in the form of `IList`s, each of which contains at most `count` items from the source Observable (the final emitted `IList` may have fewer than `count` items).

   #### `Buffer(count, skip)`

  ![Buffer(count,skip)](http://reactivex.io/documentation/operators/images/Buffer4.net.png)  `Buffer(count, skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as `IList`s. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

   #### `Buffer(bufferClosingSelector)`

  ![Buffer(bufferClosingSelector)](http://reactivex.io/documentation/operators/images/Buffer1.net.png)  When it subscribes to the source Observable, `Buffer(bufferClosingSelector)` begins to collect its emissions into an `IList`, and it also calls `bufferClosingSelector` to generate a second Observable. When this second Observable emits an `TBufferClosing` object, `Buffer` emits the current `IList` and repeats this process: beginning a new `IList` and calling `bufferClosingSelector` to create a new Observable to monitor. It will do this until the source Observable terminates.

   #### `Buffer(bufferOpenings,bufferClosingSelector)`

  ![Buffer(bufferOpenings,bufferClosingSelector)](http://reactivex.io/documentation/operators/images/Buffer2.net.png)  `Buffer(bufferOpenings, bufferClosingSelector)` monitors an Observable, `BufferOpenings`, that emits `TBufferOpening` objects. Each time it observes such an emitted item, it creates a new `IList` to begin collecting items emitted by the source Observable and it passes the `TBufferOpening` object into the `bufferClosingSelector` function. That function returns an Observable. `Buffer` monitors that Observable and when it detects an emitted item from it, it closes the `IList` and emits it as its own emission.

   #### `Buffer(timeSpan)`

  ![Buffer(timeSpan)](http://reactivex.io/documentation/operators/images/Buffer5.net.png)  `Buffer(timeSpan)` emits a new `IList` of items periodically, every `timeSpan` amount of time, containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first list, since the subscription to the source Observable. There is also a version of this variant of the operator that takes an [`IScheduler`](../scheduler) as a parameter and uses it to govern the timespan.

   #### `Buffer(timeSpan, count)`

  ![Buffer(timeSpan,count)](http://reactivex.io/documentation/operators/images/Buffer6.net.png)  `Buffer(timeSpan, count)` emits a new `IList` of items for every `count` items emitted by the source Observable, or, if `timeSpan` has elapsed since its last list emission, it emits a list of however many items the source Observable has emitted in that span, even if this is fewer than `count`. There is also a version of this variant of the operator that takes an [`IScheduler`](../scheduler) as a parameter and uses it to govern the timespan.

   #### `Buffer(timeSpan, timeShift)`

  ![Buffer(timeSpan,timeShift)](http://reactivex.io/documentation/operators/images/Buffer7.net.png)  `Buffer(timeSpan, timeShift)` creates a new `IList` of items every `timeShift` period of time, and fills this list with every item emitted by the source Observable from that time until `timeSpan` time has passed since the list’s creation, before emitting this `IList` as its own emission. If `timeSpan` is longer than `timeShift`, the emitted lists will represent time periods that overlap and so they may contain duplicate items. There is also a version of this variant of the operator that takes an [`IScheduler`](../scheduler) as a parameter and uses it to govern the timespan.

        ###  RxPHP `bufferWithCount`

       RxPHP implements this operator as `bufferWithCount`. 

  Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/bufferWithCount/bufferWithCount.php

$source = Rx\Observable::range(1, 6)
    ->bufferWithCount(2)
    ->subscribe($stdoutObserver);
```
  
```
Next value: [1,2]
Next value: [3,4]
Next value: [5,6]
Complete!
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/bufferWithCount/bufferWithCountAndSkip.php

$source = Rx\Observable::range(1, 6)
    ->bufferWithCount(2, 1)
    ->subscribe($stdoutObserver);
```
  
```
Next value: [1,2]
Next value: [2,3]
Next value: [3,4]
Next value: [4,5]
Next value: [5,6]
Next value: [6]
Complete!
```
         ###  RxPY `buffer buffer_with_count buffer_with_time buffer_with_time_or_count pairwise`

     RxPY has several Buffer variants: `buffer`, `buffer_with_count`, `buffer_with_time`, and `buffer_with_time_or_count`. For each of these variants there are optional parameters that change the behavior of the operator. As always in RxPY, when an operator may take more than one optional parameter, be sure to name the parameter in the parameter list when you call the operator so as to avoid ambiguity. 

 #### `buffer(buffer_openings)`

  ![buffer(buffer_openings)](http://reactivex.io/documentation/operators/images/buffer8.py.png)  `buffer(buffer_openings=boundaryObservable)` monitors an Observable, `buffer_openings`. Each time that Observable emits an item, it creates a new array to begin collecting items emitted by the source Observable and emits the previous array.

   #### `buffer(closing_selector)`

  ![buffer(closing_selector)](http://reactivex.io/documentation/operators/images/buffer1.py.png)  `buffer(closing_selector=closingSelector)` begins collecting items emitted by the source Observable immediately upon subscription, and also calls the `closing_selector` function to generate a second Observable. It monitors this new Observable and, when it completes or emits an item, it emits the current array, begins a new array to collect items from the source Observable, and calls `closing_selector` again to generate a new Observable to monitor in order to determine when to emit the new array. It repeats this process until the source Observable terminates, whereupon it emits the final array.

    ![buffer(closing_selector,buffer_closing_selector)](http://reactivex.io/documentation/operators/images/buffer2.py.png)  `buffer(closing_selector=openingSelector, buffer_closing_selector=closingSelector)` begins by calling `closing_selector` to get an Observable. It monitors this Observable, and, whenever it emits an item, `buffer` creates a new array, begins to collect items subsequently emitted by the source Observable into this array, and calls `buffer_closing_selector` to get a new Observable to govern the closing of that array. When this new Observable emits an item or terminates, `buffer` closes and emits the array that the Observable governs.

   #### `buffer_with_count(count)`

  ![buffer_with_count(count)](http://reactivex.io/documentation/operators/images/buffer_with_count3.py.png)  `buffer_with_count(count)` emits non-overlapping buffers in the form of arrays, each of which contains at most `count` items from the source Observable (the final emitted array may have fewer than `count` items).

   #### `buffer_with_count(count, skip)`

  ![buffer_with_count(count,skip)](http://reactivex.io/documentation/operators/images/buffer_with_count4.py.png)  `buffer_with_count(count, skip=skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as arrays. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

   #### `buffer_with_time(timespan)`

  ![buffer_with_time(timespan)](http://reactivex.io/documentation/operators/images/buffer_with_time5.py.png)  `buffer_with_time(timespan)` emits a new array of items periodically, every `timespan` milliseconds, containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first bundle, since the subscription to the source Observable. There is also a version of this variant of the operator that takes a `scheduler` parameter and uses it to govern the timespan; by default this variant uses the `timeout` scheduler.

   #### `buffer_with_time(timespan, timeshift)`

  ![buffer_with_time(timespan,timeshift)](http://reactivex.io/documentation/operators/images/buffer_with_time7.py.png)  `buffer(timespan, timeshift=timeshift)` creates a new array of items every `timeshift` milliseconds, and fills this array with every item emitted by the source Observable from that time until `timespan` milliseconds have passed since the array’s creation, before emitting this array as its own emission. If `timespan` is longer than `timeshift`, the emitted arrays will represent time periods that overlap and so they may contain duplicate items. There is also a version of this variant of the operator that takes a `scheduler` parameter and uses it to govern the timespan; by default this variant uses the `timeout` scheduler.

   #### `buffer_with_time_or_count(timespan, count)`

  ![buffer_with_time_or_count(timespan,count)](http://reactivex.io/documentation/operators/images/buffer_with_time_or_count6.py.png)  `buffer_with_time_or_count(timespan, count)` emits a new array of items for every `count` items emitted by the source Observable, or, if `timespan` milliseconds have elapsed since its last bundle emission, it emits an array of however many items the source Observable has emitted in that span, even if this is fewer than `count`. There is also a version of this variant of the operator that takes a `scheduler` parameter and uses it to govern the timespan; by default this variant uses the `timeout` scheduler.

        ###  Rxrb `buffer_with_count buffer_with_time`

     Rx.rb has three variants of the Buffer operator: 

 #### `buffer_with_count(count)`

  ![buffer_with_count(count)](http://reactivex.io/documentation/operators/images/buffer_with_count3.py.png)  `buffer_with_count(count)` emits non-overlapping buffers in the form of arrays, each of which contains at most `count` items from the source Observable (the final emitted array may have fewer than `count` items).

   #### `buffer_with_count(count,skip)`

  ![buffer_with_count(count,skip)](http://reactivex.io/documentation/operators/images/buffer_with_count4.rb.png)  `buffer_with_count(count, skip=skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as arrays. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

   #### `buffer_with_time(timespan)`

  ![buffer_with_time(timespan)](http://reactivex.io/documentation/operators/images/buffer_with_time5.py.png)  `buffer_with_time(timespan)` emits a new array of items periodically, every `timespan` milliseconds, containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first bundle, since the subscription to the source Observable.

        ###  RxScala `slidingBuffer tumblingBuffer`

     RxScala has two varieties of Buffer — `slidingBuffer` and `tumblingBuffer` — each of which has variants with different ways of assembling the buffers they emit: 

 #### `slidingBuffer(count, skip)`

  ![slidingBuffer(count,skip)](http://reactivex.io/documentation/operators/images/slidingBuffer4.png)  `slidingBuffer(count, skip)` creates a new buffer starting with the first emitted item from the source Observable, and every `skip` items thereafter, and fills each buffer with `count` items: the initial item and `count-1` subsequent ones. It emits these buffers as `Seq`s. Depending on the values of `count` and `skip` these buffers may overlap (multiple buffers may contain the same item), or they may have gaps (where items emitted by the source Observable are not represented in any buffer).

   #### `slidingBuffer(timespan, timeshift)`

  ![slidingBuffer(timespan,timeshift)](http://reactivex.io/documentation/operators/images/slidingBuffer7.png)  `slidingBuffer(timespan, timeshift)` creates a new `Seq` of items every `timeshift` (a `Duration`), and fills this buffer with every item emitted by the source Observable from that time until `timespan` (also a `Duration`) has passed since the buffer’s creation, before emitting this `Seq` as its own emission. If `timespan` is longer than `timeshift`, the emitted arrays will represent time periods that overlap and so they may contain duplicate items. There is also a version of this variant of the operator that takes a [`Scheduler`](../scheduler) as a parameter and uses it to govern the timespan.

   #### `slidingBuffer(openings, closings)`

  ![slidingBuffer(openings,closings)](http://reactivex.io/documentation/operators/images/slidingBuffer2.png)  `slidingBuffer(openings,closings)` monitors the `openings` Observable, and, whenever it emits an `Opening` item, `slidingBuffer` creates a new `Seq`, begins to collect items subsequently emitted by the source Observable into this buffer, and calls `closings` to get a new Observable to govern the closing of that buffer. When this new Observable emits an item or terminates, `slidingBuffer` closes and emits the `Seq`that the Observable governs.

   #### `tumblingBuffer(count)`

  ![tumblingBuffer(count)](http://reactivex.io/documentation/operators/images/tumblingBuffer3.png)  `tumblingBuffer(count)` emits non-overlapping buffers in the form of `Seq`s, each of which contains at most `count` items from the source Observable (the final emitted buffer may have fewer than `count` items).

   #### `tumblingBuffer(boundary)`

  ![tumblingBuffer(boundary)](http://reactivex.io/documentation/operators/images/tumblingBuffer8.png)  `tumblingBuffer(boundary)` monitors an Observable, `boundary`. Each time that Observable emits an item, it creates a new `Seq` to begin collecting items emitted by the source Observable and emits the previous `Seq`. This variant of the operator has an optional second parameter, `initialCapacity` with which you can indicate the expected size of these buffers so as to make memory allocation more efficient.

   #### `tumblingBuffer(timespan)`

  ![tumblingBuffer(timespan)](http://reactivex.io/documentation/operators/images/tumblingBuffer5.png)  `tumblingBuffer(timespan)` emits a new `Seq` of items periodically, every `timespan` (a `Duration`), containing all items emitted by the source Observable since the previous bundle emission or, in the case of the first bundle, since the subscription to the source Observable. This variant of the operator has an optional second parameter, `scheduler`, with which you can set the [`Scheduler`](../scheduler) that you want to govern the timespan calculation.

   #### `tumblingBuffer(timespan, count)`

  ![tumblingBuffer(timespan,count)](http://reactivex.io/documentation/operators/images/tumblingBuffer6.png)  `tumblingBuffer(timespan, count)` emits a new `Seq` of items for every `count` items emitted by the source Observable, or, if `timespan` (a `Duration`) has elapsed since its last bundle emission, it emits a `Seq` containing however many items the source Observable emitted in that span, even if this is fewer than `count`. This variant of the operator has an optional third parameter, `scheduler`, with which you can set the [`Scheduler`](../scheduler) that you want to govern the timespan calculation.

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/buffer.html>

Sample
======

 
> emit the most recent items emitted by an Observable within periodic time intervals

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#sample)  The Sample operator periodically looks at an Observable and emits whichever item it has most recently emitted since the previous sampling. 


 In some implementations, there is also a ThrottleFirst operator that is similar, but emits not the most-recently emitted item in the sample period, but the *first* item that was emitted during that period. 

  #### See Also

 * [Backpressure-related Operators](backpressure)
* [Debounce](debounce)
* [Window](window)
* [Introduction to Rx: Sample](http://www.introtorx.com/Content/v1.0.10621.0/13_TimeShiftedSequences.html#Sample)
* [RxMarbles: `sample`](http://rxmarbles.com/#sample)
* [101 Rx Samples: Sample — Simple](http://rxwiki.wikidot.com/101samples#toc29)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `sample throttleFirst throttleLast`

     RxGroovy implements this operator as `sample` and `throttleLast`. 


 Note that if the source Observable has emitted no items since the last time it was sampled, the Observable that results from this operator will emit no item for that sampling period. 

  ![sample](http://reactivex.io/documentation/operators/images/sample.png)  One variant of `sample` (or its alias, `throttleLast`) samples at a periodic time interval that you choose by passing in a `TimeUnit` and a quantity of such units as parameters to `sample`. 


 The following code constructs an Observable that emits the numbers between one and a million, and then samples that Observable every ten milliseconds to see what number it is emitting at that moment. 

 #### Sample Code

 
```
def numbers = Observable.range( 1, 1000000 );

numbers.sample(10, java.util.concurrent.TimeUnit.MILLISECONDS).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
339707
547810
891282
Sequence complete
```
  This variant of `sample` operates by default on the `computation` [Scheduler](../scheduler), but you can optionally pass in a Scheduler of your choosing as a third parameter. 

 * Javadoc: [`sample(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sample(long,%20java.util.concurrent.TimeUnit)) and [`throttleLast(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleLast(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`sample(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sample(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler)) and [`throttleLast(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleLast(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![sample](http://reactivex.io/documentation/operators/images/sample.o.png)  There ia also a variant of `sample` (that does not have a `throttleLast` alias) that samples the source Observable each time a second Observable emits an item (or when it terminates). You pass in that second Observable as the parameter to `sample`. 


 This variant of `sample` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`sample(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sample(rx.Observable))
   ![throttleFirst](http://reactivex.io/documentation/operators/images/throttleFirst.png)  There is also a `throttleFirst` operator, which differs from `throttleLast`/`sample` in that it emits the *first* item emitted by the source Observable in each sampling period rather than the *most recently emitted* item. 

 #### Sample Code

 
```
Scheduler s = new TestScheduler();
PublishSubject<Integer> o = PublishSubject.create();
o.throttleFirst(500, TimeUnit.MILLISECONDS, s).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
// send events with simulated time increments
s.advanceTimeTo(0, TimeUnit.MILLISECONDS);
o.onNext(1); // deliver
o.onNext(2); // skip
s.advanceTimeTo(501, TimeUnit.MILLISECONDS);
o.onNext(3); // deliver
s.advanceTimeTo(600, TimeUnit.MILLISECONDS);
o.onNext(4); // skip
s.advanceTimeTo(700, TimeUnit.MILLISECONDS);
o.onNext(5); // skip
o.onNext(6); // skip
s.advanceTimeTo(1001, TimeUnit.MILLISECONDS);
o.onNext(7); // deliver
s.advanceTimeTo(1501, TimeUnit.MILLISECONDS);
o.onCompleted();
```
 
```
1
3
7
Sequence complete
```
  `throttleFirst` operates by default on the `computation` [Scheduler](../scheduler), but you can optionally pass in a Scheduler of your choosing as a third parameter. 

 * [`throttleFirst(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleFirst(long,%20java.util.concurrent.TimeUnit))
* [`throttleFirst(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleFirst(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJava 1․x `sample throttleFirst throttleLast`

     RxJava implements this operator as `sample` and `throttleLast`. 


 Note that if the source Observable has emitted no items since the last time it was sampled, the Observable that results from this operator will emit no item for that sampling period. 

  ![sample](http://reactivex.io/documentation/operators/images/sample.png)  One variant of `sample` (or its alias, `throttleLast`) samples at a periodic time interval that you choose by passing in a `TimeUnit` and a quantity of such units as parameters to `sample`. 


 This variant of `sample` operates by default on the `computation` [Scheduler](../scheduler), but you can optionally pass in a Scheduler of your choosing as a third parameter. 

 * Javadoc: [`sample(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sample(long,%20java.util.concurrent.TimeUnit)) and [`throttleLast(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleLast(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`sample(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sample(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler)) and [`throttleLast(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleLast(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![sample](http://reactivex.io/documentation/operators/images/sample.o.png)  There ia also a variant of `sample` (that does not have a `throttleLast` alias) that samples the source Observable each time a second Observable emits an item (or when it terminates). You pass in that second Observable as the parameter to `sample`. 


 This variant of `sample` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`sample(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sample(rx.Observable))
   ![throttleFirst](http://reactivex.io/documentation/operators/images/throttleFirst.png)  There is also a `throttleFirst` operator, which differs from `throttleLast`/`sample` in that it emits the *first* item emitted by the source Observable in each sampling period rather than the *most recently emitted* item. 


 `throttleFirst` operates by default on the `computation` [Scheduler](../scheduler), but you can optionally pass in a Scheduler of your choosing as a third parameter. 

 * [`throttleFirst(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleFirst(long,%20java.util.concurrent.TimeUnit))
* [`throttleFirst(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#throttleFirst(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJS `sample throttleFirst`

     RxJS implements this operator with two variants of `sample`. 

  ![sample](http://reactivex.io/documentation/operators/images/sample.png)  The first variant accepts as its parameter a periodicity, defined as an integer number of milliseconds, and it samples the source Observable periodically at that frequency. 

 #### Sample Code

 
```
var source = Rx.Observable.interval(1000)
    .sample(5000)
    .take(2);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 3
Next: 8
Completed
```
    ![sample](http://reactivex.io/documentation/operators/images/sample.o.png)  The second variant accepts as its parameter an Observable, and it samples the source Observable whenever this second Observable emits an item. 

 #### Sample Code

 
```
var source = Rx.Observable.interval(1000)
    .sample(Rx.Observable.interval(5000))
    .take(2);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 3
Next: 8
Completed
```
    ![throttleFirst](http://reactivex.io/documentation/operators/images/throttleFirst.png)  There is also a `throttleFirst` operator, which differs from `sample` in that it emits the *first* item emitted by the source Observable in each sampling period rather than the *most recently emitted* item. 


 It does not have the variant that uses the emissions from a second Observable to regulate the sampling periodicity. 

 #### Sample Code

 
```
var times = [
    { value: 0, time: 100 },
    { value: 1, time: 600 },
    { value: 2, time: 400 },
    { value: 3, time: 900 },
    { value: 4, time: 200 }
];

// Delay each item by time and project value;
var source = Rx.Observable.from(times)
  .flatMap(function (item) {
    return Rx.Observable
      .of(item.value)
      .delay(item.time);
  })
  .throttleFirst(300 /* ms */);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 2
Next: 3
Completed
```
    `sample` and `throttleFirst` operate by default on the `timeout` [Scheduler](../scheduler). They are found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/sample.html>

Skip
====

 
> suppress the first *n* items emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#skip)  You can ignore the first *n* items emitted by an Observable and attend only to those items that come after, by modifying the Observable with the Skip operator. 

  #### See Also

 * [Last](last)
* [SkipLast](skiplast)
* [SkipUntil](skipuntil)
* [SkipWhile](skipwhile)
* [Take](take)
* [TakeLast](takelast)
* [TakeUntil](takeuntil)
* [TakeWhile](takewhile)
* [Introduction to Rx: Skip and Take](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipAndTake)
* [RxMarbles: `skip`](http://rxmarbles.com/#skip)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `skip`

     ![skip](http://reactivex.io/documentation/operators/images/skip.png)  In RxGroovy, this operator is implemented as `skip`. 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5, 6, 7, 8]);

numbers.skip(3).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
4
5
6
7
8
Sequence complete
```
  This variant of `skip` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skip(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skip(int))
   ![skip](http://reactivex.io/documentation/operators/images/skip.t.png)  There is also a variant of `skip` that takes a temporal duration rather than a quantity of items. It drops those items that are emitted during that initial duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `skip`. 


 This variant of `skip` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`skip(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skip(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`skip(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skip(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJava 1․x `skip`

     ![skip](http://reactivex.io/documentation/operators/images/skip.png)  In RxJava, this operator is implemented as `skip`. 


 This variant of `skip` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skip(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skip(int))
   ![skip](http://reactivex.io/documentation/operators/images/skip.t.png)  There is also a variant of `skip` that takes a temporal duration rather than a quantity of items. It drops those items that are emitted during that initial duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `skip`. 


 This variant of `skip` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`skip(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skip(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`skip(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skip(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJS `skip skipUntilWithTime`

     ![skip](http://reactivex.io/documentation/operators/images/skip.png)  RxJS implements the `skip` operator. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 5)
    .skip(3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 3
Next: 4
Completed
```
  `skip` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![skipUntilWithTime](http://reactivex.io/documentation/operators/images/skipUntilWithTime.png)  RxJS also implements a `skipUntilWithTime` operator that does not skip a particular quantity of items from the source Observable, but skips items based on chronology. You set this skip period by passing in a parameter to `skipUntilWithTime`, in either of these formats: 

  a number skips items from the source Observable until this many milliseconds have passed since the Observable was subscribed to a `Date`
 skips items from the source Observable until this absolute time   You may also, optionally, pass in a [Scheduler](../scheduler) as a second parameter, and the timer will operate on that Scheduler (`skipUntilWithTime` uses the `timeout` Scheduler by default). 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .skipUntilWithTime(5000);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 6
Next: 7
Next: 8
Completed
```
  `skipUntilWithTime` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `skip`

       RxPHP implements this operator as `skip`. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/skip/skip.php

use Rx\Observable\ArrayObservable;

$observable = Rx\Observable::fromArray([1, 1, 2, 3, 5, 8, 13]);
$observable
    ->skip(3)
    ->subscribe($stdoutObserver);
```
  
```
Next value: 3
Next value: 5
Next value: 8
Next value: 13
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/skip.html>

SkipLast
========

 
> suppress the final *n* items emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#skipLast)  You can ignore the final *n* items emitted by an Observable and attend only to those items that come before them, by modifying the Observable with the SkipLast operator. 

  #### See Also

 * [Last](last)
* [Skip](skip)
* [SkipUntil](skipuntil)
* [SkipWhile](skipwhile)
* [Take](take)
* [TakeLast](takelast)
* [TakeUntil](takeuntil)
* [TakeWhile](takewhile)
* [Introduction to Rx: SkipLast and TakeLast](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipLastTakeLast)
* [RxMarbles: `skipLast`](http://rxmarbles.com/#skipLast)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `skipLast`

     ![skipLast](http://reactivex.io/documentation/operators/images/skipLast.png)  You can ignore the final *n* items emitted by an Observable and attend only to those items that precede them, by modifying the Observable with the `skipLast(*n*)` operator. Note that the mechanism by which this is implemented will delay the emission of any item from the source Observable until *n* additional items have been emitted by that Observable. 


 This variant of `skipLast` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skipLast(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipLast(int))
   ![skipLast](http://reactivex.io/documentation/operators/images/skipLast.t.png)  There is also a variant of `skipLast` that takes a temporal duration rather than a quantity of items. It drops those items that are emitted during that final duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `skipLast`. 


 Note that the mechanism by which this is implemented will delay the emission of any item from the source Observable until the given duration passes since its emission. 


 This variant of `skipLast` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`skipLast(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipLast(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`skipLast(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipLast(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJava 1․x `skipLast`

     ![skipLast](http://reactivex.io/documentation/operators/images/skipLast.png)  You can ignore the final *n* items emitted by an Observable and attend only to those items that precede them, by modifying the Observable with the `skipLast(*n*)` operator. Note that the mechanism by which this is implemented will delay the emission of any item from the source Observable until *n* additional items have been emitted by that Observable. 


 This variant of `skipLast` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skipLast(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipLast(int))
   ![skipLast](http://reactivex.io/documentation/operators/images/skipLast.t.png)  There is also a variant of `skipLast` that takes a temporal duration rather than a quantity of items. It drops those items that are emitted during that final duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `skipLast`. 


 Note that the mechanism by which this is implemented will delay the emission of any item from the source Observable until the given duration passes since its emission. 


 This variant of `skipLast` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`skipLast(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipLast(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`skipLast(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipLast(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJS `skipLast skipLastWithTime`

     ![skipLast](http://reactivex.io/documentation/operators/images/skipLast.png)  You can ignore the final *n* items emitted by an Observable and attend only to those items that precede them, by modifying the Observable with the `skipLast(*n*)` operator. Note that the mechanism by which this is implemented will delay the emission of any item from the source Observable until *n* additional items have been emitted by that Observable. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 5)
    .skipLast(3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Completed
```
  `skipLast` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![skipLastWithTime](http://reactivex.io/documentation/operators/images/skipLastWithTime.png)  The `skipLastWithTime` operator takes a temporal duration rather than a quantity of items. It drops those items that are emitted during that final duration of the source Observable’s lifespan. You set this duration by passing in a number of milliseconds as a parameter to `skipLastWithTime`. 


 Note that the mechanism by which this is implemented will delay the emission of any item from the source Observable until the given duration passes since its emission. 


 `skipLastWithTime` by default operates on the `timeout` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional second parameter. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .take(10)
    .skipLastWithTime(5000);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed
```
  `skipLastWithTime` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `skipLast`

       RxPHP implements this operator as `skipLast`. 

  Bypasses a specified number of elements at the end of an observable sequence. This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/skip/skipLast.php

$observable = Rx\Observable::range(0, 5)
    ->skipLast(3);

$observable->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/skiplast.html>

Take
====

 
> emit only the first *n* items emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#take)  You can emit only the first *n* items emitted by an Observable and then complete while ignoring the remainder, by modifying the Observable with the Take operator. 

  #### See Also

 * [First](first)
* [Skip](skip)
* [SkipLast](skiplast)
* [SkipUntil](skipuntil)
* [SkipWhile](skipwhile)
* [TakeLast](takelast)
* [TakeUntil](takeuntil)
* [TakeWhile](takewhile)
* [Introduction to Rx: Skip and Take](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipAndTake)
* [RxMarbles: `take`](http://rxmarbles.com/#take)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `limit take`

     ![take](http://reactivex.io/documentation/operators/images/take.png)  In RxGroovy, this operator is implemented as `take`. 


 If you use the `take(*n*)` operator (or its synonym, `limit(*n*)`) on an Observable, and that Observable emits fewer than *n* items before completing, the new, `take`-modified Observable will not throw an exception or invoke `onError`, but will merely emit this same fewer number of items before it completes. 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5, 6, 7, 8]);

numbers.take(3).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
2
3
Sequence complete
```
  This variant of `take` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`take(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#take(int))
   ![take](http://reactivex.io/documentation/operators/images/take.t.png)  There is also a variant of `take` that takes a temporal duration rather than a quantity of items. It results in an Observable that emits only those items that are emitted during that initial duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `take`. 


 This variant of `take` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`take(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#take(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`take(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#take(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJava 1․x `limit take`

     ![take](http://reactivex.io/documentation/operators/images/take.png)  In RxJava, this operator is implemented as `take`. 


 If you use the `take(*n*)` operator (or its synonym, `limit(*n*)`) on an Observable, and that Observable emits fewer than *n* items before completing, the new, `take`-modified Observable will not throw an exception or invoke `onError`, but will merely emit this same fewer number of items before it completes. 

 #### Sample Code

 
```
Observable.just(1, 2, 3, 4, 5, 6, 7, 8)
          .take(4)
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Next: 2
Next: 3
Next: 4
Sequence complete.
```
  This variant of `take` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`take(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#take(int))
   ![take](http://reactivex.io/documentation/operators/images/take.t.png)  There is also a variant of `take` that takes a temporal duration rather than a quantity of items. It results in an Observable that emits only those items that are emitted during that initial duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `take`. 


 This variant of `take` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`take(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#take(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`take(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#take(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJS `take takeUntilWithTime`

     ![take](http://reactivex.io/documentation/operators/images/take.png)  RxJS implements the `take` operator. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 5)
    .take(3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
    ![take](http://reactivex.io/documentation/operators/images/take.0.png)  For the special case of `take(0)` you can also pass as a second parameter a [Scheduler](../scheduler) that `take` will use to immediately schedule a call to `onCompleted`. 

    `take` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

  ![takeUntilWithTime](http://reactivex.io/documentation/operators/images/takeUntilWithTime.png)  RxJS also implements a `takeUntilWithTime` operator, which is like `take` except that rather than taking a particular quantity of items, it takes all of the items that are emitted during an initial period of time. You establish this period of by passing in a parameter to `takeUntilWithTime`, in either of these formats: 

  a number mirrors items from the source Observable until this many milliseconds have passed since the Observable was subscribed to a `Date`
 mirrors items from the source Observable until this absolute time   You may also, optionally, pass in a [Scheduler](../scheduler) as a second parameter, and the timer will operate on that Scheduler (`takeUntilWithTime` uses the `timeout` Scheduler by default). 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .takeUntilWithTime(5000);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed
```
  `takeUntilWithTime` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `take takeUntil`

       RxPHP implements this operator as `take`. 

  Returns a specified number of contiguous elements from the start of an observable sequence 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/take.php

$observable = Rx\Observable::fromArray([21, 42, 63]);
$observable
    ->take(2)
    ->subscribe($stdoutObserver);
```
  
```
Next value: 21
Next value: 42
Complete!
```
      RxPHP also has an operator `takeUntil`. 

  Returns the values from the source observable sequence until the other observable sequence produces a value. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/takeUntil.php

$source = \Rx\Observable::interval(105)
    ->takeUntil(\Rx\Observable::timer(1000));

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Next value: 5
Next value: 6
Next value: 7
Next value: 8
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/take.html>

TimeInterval
============

 
> convert an Observable that emits items into one that emits indications of the amount of time elapsed between those emissions

  ![TimeInterval](http://reactivex.io/documentation/operators/images/timeInterval.c.png)  The TimeInterval operator intercepts the items from the source Observable and emits in their place objects that indicate the amount of time that elapsed between pairs of emissions. 

  #### See Also

 * [Timestamp](timestamp)
* [Introduction to Rx: Timestamp and TimeInterval](http://www.introtorx.com/Content/v1.0.10621.0/08_Transformation.html#TimeStampAndTimeInterval)
* [101 Rx Samples: Interval — With TimeInterval()](http://rxwiki.wikidot.com/101samples#toc31)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `timeInterval`

     ![timeInterval](http://reactivex.io/documentation/operators/images/timeInterval.png)  The timeInterval operator converts a source Observable into an Observable that emits indications of the amount of time lapsed between consecutive emissions of the source Observable. The first emission from this new Observable indicates the amount of time lapsed between the time when the observer subscribed to the Observable and the time when the source Observable emitted its first item. There is no corresponding emission marking the amount of time lapsed between the last emission of the source Observable and the subsequent call to `onCompleted`. 


 `timeInterval` by default operates on the `immediate` [Scheduler](../scheduler), but also has a variant that allows you to specify the Scheduler by passing it in as a parameter. 

 * Javadoc: [`timeInterval()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeInterval())
* Javadoc: [`timeInterval(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeInterval(rx.Scheduler))
       ###  RxJava 1․x `timeInterval`

     ![timeInterval](http://reactivex.io/documentation/operators/images/timeInterval.png)  The timeInterval operator converts a source Observable into an Observable that emits indications of the amount of time lapsed between consecutive emissions of the source Observable. The first emission from this new Observable indicates the amount of time lapsed between the time when the observer subscribed to the Observable and the time when the source Observable emitted its first item. There is no corresponding emission marking the amount of time lapsed between the last emission of the source Observable and the subsequent call to `onCompleted`. 


 `timeInterval` by default operates on the `immediate` [Scheduler](../scheduler), but also has a variant that allows you to specify the Scheduler by passing it in as a parameter. 

 * Javadoc: [`timeInterval()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeInterval())
* Javadoc: [`timeInterval(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeInterval(rx.Scheduler))
       ###  RxJS `timeInterval`

     ![timeInterval](http://reactivex.io/documentation/operators/images/timeInterval.png)  The `timeInterval` operator converts a source Observable into an Observable that emits indications of the amount of time lapsed between consecutive emissions of the source Observable. The first emission from this new Observable indicates the amount of time lapsed between the time when the observer subscribed to the Observable and the time when the source Observable emitted its first item. There is no corresponding emission marking the amount of time lapsed between the last emission of the source Observable and the subsequent call to `onCompleted`. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .timeInterval()
    .map(function (x) { return x.value + ':' + x.interval; })
    .take(5);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0:0
Next: 1:1000
Next: 2:1000
Next: 3:1000
Next: 4:1000
Completed
```
  `timeInterval` by default operates on the `timeout` [Scheduler](../scheduler), but also has a variant that allows you to specify the Scheduler by passing it in as a parameter. 


 `timeInterval` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`
     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/timeinterval.html>

Timer
=====

 
> create an Observable that emits a particular item after a given delay

  ![Timer](http://reactivex.io/documentation/operators/images/timer.c.png)  The Timer operator creates an Observable that emits one particular item after a span of time that you specify. 

  #### See Also

 * [From](from)
* [Interval](interval)
* [Just](just)
* [Introduction to Rx: Timer](http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableTimer)
* [101 Rx Samples: Timer — Simple](http://rxwiki.wikidot.com/101samples#toc34)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `timer`

    RxGroovy implements this operator as `timer`.

  ![timer](http://reactivex.io/documentation/operators/images/timer.png)  `timer` returns an Observable that emits a single number zero after a delay period you specify. 


 `timer` by default operates on the `computation` [Scheduler](../scheduler), or you can override this by passing in a Scheduler as a final parameter. 

 * Javadoc: [`timer(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timer(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`timer(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timer(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJava 1․x `timer`

    RxJava implements this operator as `timer`.

  ![timer](http://reactivex.io/documentation/operators/images/timer.png)  `timer` returns an Observable that emits a single number zero after a delay period you specify. 


 `timer` by default operates on the `computation` [Scheduler](../scheduler), or you can override this by passing in a Scheduler as a final parameter. 

 * Javadoc: [`timer(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timer(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`timer(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timer(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJS `timer`

    In RxJS there are two versions of the `timer` operator.

  ![timer](http://reactivex.io/documentation/operators/images/timer.j1.png)  The first version of `timer` returns an Observable that emits a single item after a delay period you specify. You can specify the delay either as a `Date` object (which means, delay until that absolute moment) or as an integer (which means, delay that many milliseconds). 

    ![timer](http://reactivex.io/documentation/operators/images/timer.j2.png)  There is also a version of `timer` that returns an Observable that emits a single item after a specified delay, and then emits items periodically thereafter on a specified periodicity. In this way it behaves a bit more like the [Interval](interval) operator. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(200, 100)
    .timeInterval()
    .pluck('interval')
    .take(3);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```


```
Next: 200
Next: 100
Next: 100
Completed
```
    `timer` by default operates on the `timeout` [Scheduler](../scheduler), or you can override this by passing in a Scheduler as a final parameter. 


 `timer` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `timer`

       RxPHP implements this operator as `timer`. 

  Returns an observable sequence that produces a value after dueTime has elapsed. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/timer/timer.php

$source = \Rx\Observable::timer(200);

$source->subscribe($createStdoutObserver());
```
  
```
Next value: 0
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/timer.html>

Timestamp
=========

 
> attach a timestamp to each item emitted by an Observable indicating when it was emitted

  ![Timestamp](http://reactivex.io/documentation/operators/images/timestamp.c.png)  The Timestamp operator attaches a timestamp to each item emitted by the source Observable before reemitting that item in its own sequence. The timestamp indicates at what time the item was emitted. 

  #### See Also

 * [Timestamp](timestamp)
* [Introduction to Rx: Timestamp and TimeInterval](http://www.introtorx.com/Content/v1.0.10621.0/08_Transformation.html#TimeStampAndTimeInterval)
* [101 Rx Samples: Timestamp](http://rxwiki.wikidot.com/101samples#toc35)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `timestamp`

     ![timestamp](http://reactivex.io/documentation/operators/images/timestamp.png)  The `timestamp` method converts an Observable that emits items of type *T* into one that emits objects of type `Timestamped<*T*>`, where each such object is stamped with the time at which it was originally emitted. 

 
```
def myObservable = Observable.range(1, 1000000).filter({ 0 == (it % 200000) });

myObservable.timestamp().subscribe(
  { println(it.toString()); },               // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
Timestamped(timestampMillis = 1369252582698, value = 200000)
Timestamped(timestampMillis = 1369252582740, value = 400000)
Timestamped(timestampMillis = 1369252582782, value = 600000)
Timestamped(timestampMillis = 1369252582823, value = 800000)
Timestamped(timestampMillis = 1369252582864, value = 1000000)
Sequence complete
```
  `timestamp` by default operates on the `immediate` [Scheduler](../scheduler) but also has a variant that allows you to choose the Scheduler by passing it in as a parameter. 

 * Javadoc: [`timestamp()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timestamp())
* Javadoc: [`timestamp(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timestamp(rx.Scheduler))
       ###  RxJava 1․x `timestamp`

     ![timestamp](http://reactivex.io/documentation/operators/images/timestamp.png)  The `timestamp` method converts an Observable that emits items of type *T* into one that emits objects of type `Timestamped<*T*>`, where each such object is stamped with the time at which it was originally emitted. 


 `timestamp` by default operates on the `immediate` [Scheduler](../scheduler) but also has a variant that allows you to choose the Scheduler by passing it in as a parameter. 

 * Javadoc: [`timestamp()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timestamp())
* Javadoc: [`timestamp(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timestamp(rx.Scheduler))
       ###  RxJS `timestamp`

     ![timestamp](http://reactivex.io/documentation/operators/images/timestamp.png)  The `timestamp` method attaches a timestamp to each item emitted by the source Observable before emitting that item as part of its own sequence. The timestamp indicates when the item was emitted by the source Observable. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .timestamp()
    .map(function (x) { return x.value + ':' + x.timestamp; })
    .take(5);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0:1378690776351
Next: 1:1378690777313
Next: 2:1378690778316
Next: 3:1378690779317
Next: 4:1378690780319
Completed
```
  `timestamp` by default operates on the `timeout` [Scheduler](../scheduler), but also has a variant that allows you to specify the Scheduler by passing it in as a parameter. 


 `timestamp` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`
       ###  RxPHP `timestamp`

       RxPHP implements this operator as `timestamp`. 

  Records the timestamp for each value in an observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/timestamp/timestamp.php

$source = \Rx\Observable::interval(1000)
    ->timestamp()
    ->map(function (\Rx\Timestamped $x) {
        return $x->getValue() . ':' . $x->getTimestampMillis();
    })
    ->take(5);

$source->subscribe($createStdoutObserver());

// Next value: 0:1460781738354
// Next value: 1:1460781739358
// Next value: 2:1460781740359
// Next value: 3:1460781741362
// Next value: 4:1460781742367
// Complete!
```
  
```
Next value: 0:1489535638531
Next value: 1:1489535639534
Next value: 2:1489535640532
Next value: 3:1489535641528
Next value: 4:1489535642528
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/timestamp.html>

RefCount
========

 
> make a Connectable Observable behave like an ordinary Observable

  ![RefCount](http://reactivex.io/documentation/operators/images/publishRefCount.c.png)  A connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when the Connect operator is applied to it. In this way you can prompt an Observable to begin emitting items at a time of your choosing. 


 The RefCount operator automates the process of connecting to and disconnecting from a connectable Observable. It operates on a connectable Observable and returns an ordinary Observable. When the first observer subscribes to this Observable, RefCount connects to the underlying connectable Observable. RefCount then keeps track of how many other observers subscribe to it and does not disconnect from the underlying connectable Observable until the last observer has done so. 

  #### See Also

 * [Connect](connect)
* [Publish](publish)
* [Replay](replay)
* [Introduction to Rx: RefCount](http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#RefCount)
* [Wedding Party: Share, Publish, Refcount, and All That Jazz](http://blog.kaush.co/2015/01/21/rxjava-tip-for-the-day-share-publish-refcount-and-all-that-jazz/) by Kaushik Gopal

 Language-Specific Information
-----------------------------

    ###  RxGroovy `refCount share`

     ![refCount](http://reactivex.io/documentation/operators/images/publishRefCount.png)  RxGroovy implements this operator as `refCount`. 

 * Javadoc: [`refCount()`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html#refCount())
   There is also a `share` operator, which is the equivalent of applying both the `publish` and `refCount` operators to an Observable, in that order. 

 * Javadoc: [`share()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#share())

      ###  RxJava 1․x `refCount share`

     ![refCount](http://reactivex.io/documentation/operators/images/publishRefCount.png)  RxJava implements this operator as `refCount`. 

 * Javadoc: [`refCount()`](http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html#refCount())
   There is also a `share` operator, which is the equivalent of applying both the `publish` and `refCount` operators to an Observable, in that order. 

 * Javadoc: [`share()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#share())

      ###  RxJS `refCount share shareValue`

     ![refCount](http://reactivex.io/documentation/operators/images/publishRefCount.png)  RxJava implements this operator as `refCount`. 

 #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(2)
    .doAction(function (x) { console.log('Side effect'); });

var published = source.publish().refCount();

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Side effect
Next: SourceA0
Next: SourceB0
Side effect
Next: SourceA1
Next: SourceB1
Completed
Completed
```
  `refCount` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.binding.js` (requires `rx.js`, `rx.compat.js`, `rx.lite.js`, or `rx.lite.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

    There is also a `share` operator, which is the equivalent of applying both the `publish` and `refCount` operators to an Observable, in that order. A variant called `shareValue` takes as a parameter a single item that it will emit to any subscribers before beginning to emit items from the source Observable. 

 #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(2)
    .do(
        function (x) { console.log('Side effect'); });

var published = source.share();

// When the number of observers subscribed to published observable goes from
// 0 to 1, we connect to the underlying observable sequence.
published.subscribe(createObserver('SourceA'));
// When the second subscriber is added, no additional subscriptions are added to the
// underlying observable sequence. As a result the operations that result in side
// effects are not repeated per subscriber.
published.subscribe(createObserver('SourceB'));

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Side effect
Next: SourceA0
Next: SourceB0
Side effect
Next: SourceA1
Next: SourceB1
Completed
```
  `share` and `shareValue` are found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.binding.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `share singleInstance shareValue`

       RxPHP implements this operator as `share`. 

  Returns an observable sequence that shares a single subscription to the underlying sequence. This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/share/share.php

//With Share
$source = \Rx\Observable::interval(1000)
    ->take(2)
    ->doOnNext(function ($x) {
        echo "Side effect\n";
    });

$published = $source->share();

$published->subscribe($createStdoutObserver('SourceA '));
$published->subscribe($createStdoutObserver('SourceB '));
```
  
```
Side effect
SourceA Next value: 0
SourceB Next value: 0
Side effect
SourceA Next value: 1
SourceB Next value: 1
SourceA Complete!
SourceB Complete!
```
      RxPHP also has an operator `singleInstance`. 

  Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence can be resubscribed to, even if all prior subscriptions have ended. This operator behaves like share() in RxJS 5 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/share/singleInstance.php

$interval = Rx\Observable::interval(1000);

$source = $interval
    ->take(2)
    ->do(function () {
        echo 'Side effect', PHP_EOL;
    });

$single = $source->singleInstance();

// two simultaneous subscriptions, lasting 2 seconds
$single->subscribe($createStdoutObserver('SourceA '));
$single->subscribe($createStdoutObserver('SourceB '));

\Rx\Observable::timer(5000)->subscribe(function () use ($single, &$createStdoutObserver) {
    // resubscribe two times again, more than 5 seconds later,
    // long after the original two subscriptions have ended
    $single->subscribe($createStdoutObserver('SourceC '));
    $single->subscribe($createStdoutObserver('SourceD '));
});
```
  
```
Side effect
SourceA Next value: 0
SourceB Next value: 0
Side effect
SourceA Next value: 1
SourceB Next value: 1
SourceA Complete!
SourceB Complete!
Side effect
SourceC Next value: 0
SourceD Next value: 0
Side effect
SourceC Next value: 1
SourceD Next value: 1
SourceC Complete!
SourceD Complete!
```
      RxPHP also has an operator `shareValue`. 

  Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/share/shareValue.php

$source = \Rx\Observable::interval(1000)
    ->take(2)
    ->doOnNext(function ($x) {
        echo "Side effect\n";
    });

$published = $source->shareValue(42);

$published->subscribe($createStdoutObserver('SourceA '));
$published->subscribe($createStdoutObserver('SourceB '));
```
  
```
SourceA Next value: 42
SourceB Next value: 42
Side effect
SourceA Next value: 0
SourceB Next value: 0
Side effect
SourceA Next value: 1
SourceB Next value: 1
SourceA Complete!
SourceB Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/refcount.html>

Implementing Your Own Operators
===============================

 You can implement your own Observable operators. This page shows you how.

 If your operator is designed to *originate* an Observable, rather than to transform or react to a source Observable, use the [`create( )`](operators/create) method rather than trying to implement `Observable` manually. Otherwise, follow the instructions below.

 Chaining Your Custom Operators with Standard RxJava Operators
-------------------------------------------------------------

 The following example shows how you can chain a custom operator (in this example: `myOperator`) along with standard RxJava operators by using the `lift( )` operator:

 
```
Observable foo = barObservable.ofType(Integer).map({it*2}).lift(new myOperator<T>()).map({"transformed by myOperator: " + it});
```
 The following section will show how to form the scaffolding of your operator so that it will work correctly with `lift( )`.

 Implementing Your Operator
--------------------------

 Define your operator as a public class that implements the [`Operator`](http://reactivex.io/RxJava/javadoc/rx/Observable.Operator.html) interface, like so:

 
```
public class myOperator<T> implements Operator<T> {
  public myOperator( /* any necessary params here */ ) {
    /* any necessary initialization here */
  }

  @Override
  public Subscriber<? super T> call(final Subscriber<? super T> s) {
    return new Subscriber<t>(s) {
      @Override
      public void onCompleted() {
        /* add your own onCompleted behavior here, or just pass the completed notification through: */
        if(!s.isUnsubscribed()) {
          s.onCompleted();
        }
      }

      @Override
      public void onError(Throwable t) {
        /* add your own onError behavior here, or just pass the error notification through: */
        if(!s.isUnsubscribed()) {
          s.onError(t);
        }
      }

      @Override
      public void onNext(T item) {
        /* this example performs some sort of simple transformation on each incoming item and then passes it along */
        if(!s.isUnsubscribed()) {
          transformedItem = myOperatorTransformOperation(item);
          s.onNext(transformedItem);
        }
      }
    };
  }
}
```
 Other Considerations
--------------------

 * Your operator should check [its Subscriber's `isUnsubscribed( )` status](observable#unsubscribing) before it emits any item to (or sends any notification to) the Subscriber. Do not waste time generating items that no Subscriber is interested in seeing.
* Your operator should obey the core tenets of the Observable contract:
	+ It may call a Subscriber's [`onNext( )`](observable#onnext-oncompleted-and-onerror) method any number of times, but these calls must be non-overlapping.
	+ It may call either a Subscriber's [`onCompleted( )`](observable#onnext-oncompleted-and-onerror) or [`onError( )`](observable#onnext-oncompleted-and-onerror) method, but not both, exactly once, and it may not subsequently call a Subscriber's [`onNext( )`](observable#onnext-oncompleted-and-onerror) method.
	+ If you are unable to guarantee that your operator conforms to the above two tenets, you can add the [`serialize( )`](observable-utility-operators#serialize) operator to it to force the correct behavior.
* Do not block within your operator.
* It is usually best that you compose new operators by combining existing ones, to the extent that this is possible, rather than reinventing the wheel. RxJava itself does this with some of its standard operators, for example:
	+ [`first( )`](filtering-observables#wiki-first-and-takefirst) is defined as [`take(1)`](filtering-observables#wiki-take)`.`[`single( )`](observable-utility-operators#wiki-single-and-singleordefault)
	+ [`ignoreElements( )`](filtering-observables#wiki-ignoreelements) is defined as [`filter(alwaysFalse( ))`](filtering-observables#wiki-filter)
	+ [`reduce(a)`](mathematical-and-aggregate-operators#wiki-reduce) is defined as [`scan(a)`](transforming-observables#wiki-scan)`.`[`last( )`](filtering-observables#wiki-last)
* If your operator uses functions or lambdas that are passed in as parameters (predicates, for instance), note that these may be sources of exceptions, and be prepared to catch these and notify subscribers via `onError( )` calls.
* In general, notify subscribers of error conditions immediately, rather than making an effort to emit more items first.
* In some ReactiveX implementations, your operator may need to be sensitive to that implementation’s “backpressure” strategies. (See, for example: [Pitfalls of Operator Implementations (part 2)](http://akarnokd.blogspot.hu/2015/05/pitfalls-of-operator-implementations_14.html) by Dávid Karnok.)

 See Also
--------

 * [Pitfalls of Operator Implementations (part 1)](http://akarnokd.blogspot.hu/2015/05/pitfalls-of-operator-implementations.html) and [(part 2)](http://akarnokd.blogspot.hu/2015/05/pitfalls-of-operator-implementations_14.html) by Dávid Karnok.
* [Implementing Your Own Observable Operators](http://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/implementing_your_own_operators.html) (in RxJS) by Dennis Stoyanov



 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/implement-operator.html>

Retry
=====

 
> if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error

  ![Retry](http://reactivex.io/documentation/operators/images/retry.C.png)  The Retry operator responds to an `onError` notification from the source Observable by not passing that call through to its observers, but instead by resubscribing to the source Observable and giving it another opportunity to complete its sequence without error. Retry always passes `onNext` notifications through to its observers, even from sequences that terminate with an error, so this can cause duplicate emissions (as shown in the diagram above). 

  #### See Also

 * [Catch](catch)
* [Introduction to Rx: Retry](http://www.introtorx.com/Content/v1.0.10621.0/11_AdvancedErrorHandling.html#Retry)

 Language-Specific Information
-----------------------------

    ###  RxClojure

     RxClojure does not implement the Retry operator. 

      ###  RxCpp `retry`

     RxCpp implements this operator as `retry`: 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  `retry` takes a single argument, a count of the number of times it should try resubscribing to the source Observable when it encounters errors. If this count is exceeded, `retry` will not attempt to resubscribe and will instead pass the `onError` notification to its observers. 

       ###  RxGroovy `retry retryWhen`

     RxGroovy has two versions of this operator: `retry` and `retryWhen`. 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  One variant of `retry` takes no parameters. It will continue to resubscribe to and mirror the source Observable no matter how many `onError` notifications it receives. 


 Another variant of `retry` takes a single parameter: a count of the number of times it should try to resubscribe to the source Observable when it encounters errors. If this count is exceeded, `retry` will not attempt to resubscribe again and will instead pass the latest `onError` notification to its observers. 


 A third variant of `retry` takes a predicate function as a parameter. You write this function to accept two arguments: an Integer count of how many retries have taken place thusfar, and a Throwable indicating the error that caused the `onError` notification. This function returns a Boolean to indicate whether or not `retry` should resubscribe to and mirror the source Observable. If it does not, then `retry` passes the latest `onError` notification to its observers. 


 `retry` by default operates on the `trampoline` [Scheduler](../scheduler). 

 * Javadoc: [`retry()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retry())
* Javadoc: [`retry(long)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retry(long))
* Javadoc: [`retry(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retry(rx.functions.Func2))
   ![retryWhen](http://reactivex.io/documentation/operators/images/retryWhen.f.png)  The `retryWhen` operator is similar to `retry` but decides whether or not to resubscribe to and mirror the source Observable by passing the Throwable from the `onError` notification to a function that generates a second Observable, and observes its result to determine what to do. If that result is an emitted item, `retryWhen` resubscribes to and mirrors the source and the process repeats; if that result is an `onError` notification, `retryWhen` passes this notification on to its observers and terminates. 


 `retryWhen` by default operates on the `trampoline` [Scheduler](../scheduler), and there is also a version that accepts a Scheduler as a parameter. 

 * Javadoc: [`retryWhen(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retryWhen(rx.functions.Func1))
* Javadoc: [`retryWhen(Func1,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retryWhen(rx.functions.Func1,%20rx.Scheduler))
       ###  RxJava 1․x `retry retryWhen`

     RxJava has two versions of this operator: `retry` and `retryWhen`. 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  One variant of `retry` takes no parameters. It will continue to resubscribe to and mirror the source Observable no matter how many `onError` notifications it receives. 


 Another variant of `retry` takes a single parameter: a count of the number of times it should try to resubscribe to the source Observable when it encounters errors. If this count is exceeded, `retry` will not attempt to resubscribe again and will instead pass the latest `onError` notification to its observers. 


 A third variant of `retry` takes a predicate function as a parameter. You write this function to accept two arguments: an Integer count of how many retries have taken place thusfar, and a Throwable indicating the error that caused the `onError` notification. This function returns a Boolean to indicate whether or not `retry` should resubscribe to and mirror the source Observable. If it does not, then `retry` passes the latest `onError` notification to its observers. 


 `retry` by default operates on the `trampoline` [Scheduler](../scheduler). 

 * Javadoc: [`retry()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retry())
* Javadoc: [`retry(long)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retry(long))
* Javadoc: [`retry(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retry(rx.functions.Func2))
   ![retryWhen](http://reactivex.io/documentation/operators/images/retryWhen.f.png)  The `retryWhen` operator is similar to `retry` but decides whether or not to resubscribe to and mirror the source Observable by passing the Throwable from the `onError` notification to a function that generates a second Observable, and observes its result to determine what to do. If that result is an emitted item, `retryWhen` resubscribes to and mirrors the source and the process repeats; if that result is an `onError` notification, `retryWhen` passes this notification on to its observers and terminates. 


 `retryWhen` by default operates on the `trampoline` [Scheduler](../scheduler), and there is also a version that accepts a Scheduler as a parameter. 

 #### Sample Code

 
```
Observable.create((Subscriber<? super String> s) -> {
      System.out.println("subscribing");
      s.onError(new RuntimeException("always fails"));
  }).retryWhen(attempts -> {
      return attempts.zipWith(Observable.range(1, 3), (n, i) -> i).flatMap(i -> {
          System.out.println("delay retry by " + i + " second(s)");
          return Observable.timer(i, TimeUnit.SECONDS);
      });
  }).toBlocking().forEach(System.out::println);
```
 
```
subscribing
delay retry by 1 second(s)
subscribing
delay retry by 2 second(s)
subscribing
delay retry by 3 second(s)
subscribing
```
 * Javadoc: [`retryWhen(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retryWhen(rx.functions.Func1))
* Javadoc: [`retryWhen(Func1,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#retryWhen(rx.functions.Func1,%20rx.Scheduler))
       ###  RxJS `retry`

     RxJS implements this operator as `retry`. 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  One variant of `retry` takes no parameters. It will continue to resubscribe to and mirror the source Observable no matter how many `onError` notifications it receives. 


 Another variant of `retry` takes a single parameter: a count of the number of `onError` notification it should be willing to accept before it too fails and passes the `onError` to its observers. For example, `retry(2)` means that `retry` will resubscribe to and mirror the source Observable the first time it receives an `onError` notification, but will terminate with an error the second time this happens. 

   `retry` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxKotlin `retry retryWhen`

     RxKotlin has two versions of this operator: `retry` and `retryWhen`. 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  One variant of `retry` takes no parameters. It will continue to resubscribe to and mirror the source Observable no matter how many `onError` notifications it receives. 


 Another variant of `retry` takes a single parameter: a count of the number of times it should try to resubscribe to the source Observable when it encounters errors. If this count is exceeded, `retry` will not attempt to resubscribe again and will instead pass the latest `onError` notification to its observers. 


 A third variant of `retry` takes a predicate function as a parameter. You write this function to accept two arguments: an Integer count of how many retries have taken place thusfar, and a Throwable indicating the error that caused the `onError` notification. This function returns a Boolean to indicate whether or not `retry` should resubscribe to and mirror the source Observable. If it does not, then `retry` passes the latest `onError` notification to its observers. 

   ![retryWhen](http://reactivex.io/documentation/operators/images/retryWhen.f.png)  The `retryWhen` operator is similar to `retry` but decides whether or not to resubscribe to and mirror the source Observable by passing the Throwable from the `onError` notification to a function that generates a second Observable, and observes its result to determine what to do. If that result is an emitted item, `retryWhen` resubscribes to and mirrors the source and the process repeats; if that result is an `onError` notification, `retryWhen` passes this notification on to its observers and terminates. 

       ###  RxNET `Retry`

     Rx.NET implements this operator as `Retry`. 

  ![Retry](http://reactivex.io/documentation/operators/images/retry.C.png)  One variant of `Retry` takes no parameters. It will continue to resubscribe to and mirror the source Observable no matter how many `onError` notifications it receives. 


 Another variant of `Retry` takes a single parameter: a count of the number of `onError` notification it should be willing to accept before it too fails and passes the `onError` to its observers. For example, `Retry(2)` means that `Retry` will resubscribe to and mirror the source Observable the first time it receives an `onError` notification, but will terminate with an error the second time this happens. 

       ###  RxPHP `retry retryWhen`

       RxPHP implements this operator as `retry`. 

  Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. Note if you encounter an error and want it to retry once, then you must use ->retry(2). 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/retry/retry.php

$count = 0;

$observable = Rx\Observable::interval(1000)
    ->flatMap(function ($x) use (&$count) {
        if (++$count < 2) {
            return Rx\Observable::error(new \Exception('Something'));
        }
        return Rx\Observable::of(42);
    })
    ->retry(3)
    ->take(1);

$observable->subscribe($stdoutObserver);
```
  
```
Next value: 42
Complete!
```
      RxPHP also has an operator `retryWhen`. 

  Repeats the source observable sequence on error when the notifier emits a next value. If the source observable errors and the notifier completes, it will complete the source sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/retry/retryWhen.php

$source = Rx\Observable::interval(1000)
    ->map(function ($n) {
        if ($n === 2) {
            throw new Exception();
        }
        return $n;
    })
    ->retryWhen(function (\Rx\Observable $errors) {
        return $errors->delay(200);
    })
    ->take(6);

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 0
Next value: 1
Next value: 0
Next value: 1
Next value: 0
Next value: 1
Complete!
```
         ###  RxPY `retry`

     RxPY implements this operator as `retry`: 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  `retry` takes a single optional parameter, a count of the number of times it should try resubscribing to and mirroring the source Observable when it encounters errors. If this count is exceeded, `retry` will not attempt to resubscribe and will instead pass the `onError` notification to its observers. If you omit this parameter, `retry` will attempt to resubscribe and mirror indefinitely, no matter how many `onError` notifications it receives. 

       ###  Rxrb `retry retry_infinitely`

     Rx.rb has two versions of this operator: `retry` and `retry_infinitely`. 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  `retry` takes a single optional parameter, a count of the number of times it should try resubscribing to and mirroring the source Observable when it encounters errors. If this count is exceeded, `retry` will not attempt to resubscribe and will instead pass the `onError` notification to its observers. 

   `retryInfinitely`, on the other hand, will attempt to resubscribe to and mirror the source Observable indefinitely, no matter how many `onError` notifications it receives. 

      ###  RxScala `retry retryWhen`

     RxScala has two versions of this operator: `retry` and `retryWhen`. 

  ![retry](http://reactivex.io/documentation/operators/images/retry.png)  One variant of `retry` takes no parameters. It will continue to resubscribe to and mirror the source Observable no matter how many `onError` notifications it receives. 


 Another variant of `retry` takes a single parameter: a count of the number of times it should try to resubscribe to the source Observable when it encounters errors. If this count is exceeded, `retry` will not attempt to resubscribe again and will instead pass the latest `onError` notification to its observers. 


 A third variant of `retry` takes a predicate function as a parameter. You write this function to accept two arguments: an Int count of how many retries have taken place thusfar, and a Throwable indicating the error that caused the `onError` notification. This function returns a Boolean to indicate whether or not `retry` should resubscribe to and mirror the source Observable. If it does not, then `retry` passes the latest `onError` notification to its observers. 

   ![retryWhen](http://reactivex.io/documentation/operators/images/retryWhen.f.png)  The `retryWhen` operator is similar to `retry` but decides whether or not to resubscribe to and mirror the source Observable by passing the Throwable from the `onError` notification to a function that generates a second Observable, and observes its result to determine what to do. If that result is an emitted item, `retryWhen` resubscribes to and mirrors the source and the process repeats; if that result is an `onError` notification, `retryWhen` passes this notification on to its observers and terminates. 

     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/retry.html>

TakeLast
========

 
> emit only the final *n* items emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#takeLast)  You can emit only the final *n* items emitted by an Observable and ignore those items that come before them, by modifying the Observable with the TakeLast operator. 

  #### See Also

 * [Last](last)
* [Skip](skip)
* [SkipLast](skiplast)
* [SkipUntil](skipuntil)
* [SkipWhile](skipwhile)
* [Take](take)
* [TakeUntil](takeuntil)
* [TakeWhile](takewhile)
* [Introduction to Rx: SkipLast and TakeLast](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipLastTakeLast)
* [RxMarbles: `takeLast`](http://rxmarbles.com/#takeLast)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `takeLast takeLastBuffer`

     ![takeLast](http://reactivex.io/documentation/operators/images/takeLast.n.png)  You can emit only the final *n* items emitted by an Observable and ignore those items that precede them, by modifying the Observable with the `takeLast(*n*)` operator. Note that this will delay the emission of any item from the source Observable until the source Observable completes. 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);

numbers.takeLast(2).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
8
9
Sequence complete
```
  This variant of `takeLast` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`takeLast(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(int))
   ![takeLast](http://reactivex.io/documentation/operators/images/takeLast.t.png)  There is also a variant of `takeLast` that takes a temporal duration rather than a quantity of items. It emits only those items that are emitted during that final duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `takeLast`. 


 Note that this will delay the emission of any item from the source Observable until the source Observable completes. 


 This variant of `takeLast` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`takeLast(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLast(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![takeLast](http://reactivex.io/documentation/operators/images/takeLast.tn.png)  There is also a variant that combines the two methods. It emits the minimum of the number of items emitted during a specified time window *or* a particular count of items. 


 This variant of `takeLast` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional fourth parameter. 

 * Javadoc: [`takeLast(int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLast(int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![takeLastBuffer](http://reactivex.io/documentation/operators/images/takeLastBuffer.png)  There is also an operator called `takeLastBuffer`. It exists in the same set of variants as described above for `takeLast`, and only differs in behavior by emitting its items not individually but collected into a single `List` of items that is emitted as a single item. 

 * Javadoc: [`takeLastBuffer(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(int))
* Javadoc: [`takeLastBuffer(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLastBuffer(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
* Javadoc: [`takeLastBuffer(int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLastBuffer(int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJava 1․x `takeLast takeLastBuffer`

     ![takeLast](http://reactivex.io/documentation/operators/images/takeLast.n.png)  You can emit only the final *n* items emitted by an Observable and ignore those items that precede them, by modifying the Observable with the `takeLast(*n*)` operator. Note that this will delay the emission of any item from the source Observable until the source Observable completes. 


 This variant of `takeLast` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`takeLast(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(int))
   ![takeLast](http://reactivex.io/documentation/operators/images/takeLast.t.png)  There is also a variant of `takeLast` that takes a temporal duration rather than a quantity of items. It emits only those items that are emitted during that final duration of the source Observable’s lifespan. You set this duration by passing in a length of time and the time units this length is denominated in as parameters to `takeLast`. 


 Note that this will delay the emission of any item from the source Observable until the source Observable completes. 


 This variant of `takeLast` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional third parameter. 

 * Javadoc: [`takeLast(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLast(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![takeLast](http://reactivex.io/documentation/operators/images/takeLast.tn.png)  There is also a variant that combines the two methods. It emits the minimum of the number of items emitted during a specified time window *or* a particular count of items. 


 This variant of `takeLast` by default operates on the `computation` [Scheduler](../scheduler), but you may also pass in a Scheduler of your choosing as an optional fourth parameter. 

 * Javadoc: [`takeLast(int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLast(int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLast(int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![takeLastBuffer](http://reactivex.io/documentation/operators/images/takeLastBuffer.png)  There is also an operator called `takeLastBuffer`. It exists in the same set of variants as described above for `takeLast`, and only differs in behavior by emitting its items not individually but collected into a single `List` of items that is emitted as a single item. 

 * Javadoc: [`takeLastBuffer(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(int))
* Javadoc: [`takeLastBuffer(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLastBuffer(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
* Javadoc: [`takeLastBuffer(int,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(int,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`takeLastBuffer(int,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeLastBuffer(int,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
       ###  RxJS `takeLast takeLastBuffer takeLastBufferWithTime takeLastWithTime`

     ![takeLast](http://reactivex.io/documentation/operators/images/takeLast.n.png)  You can emit only the final *n* items emitted by an Observable and ignore those items that precede them, by modifying the Observable with the `takeLast(*n*)` operator. Note that this will delay the emission of any item from the source Observable until that Observable completes. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 5)
    .takeLast(3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 2
Next: 3
Next: 4
Completed
```
  `takeLast` is found in each of the following distributions: 

 * `rx.js`
* `rx.alljs`
* `rx.all.compatjs`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![takeLastWithTime](http://reactivex.io/documentation/operators/images/takeLastWithTime.png)  The `takeLastWithTime` operator takes a temporal duration rather than a quantity of items. It emits only those items that are emitted during that final duration of the source Observable’s lifespan. You set this duration by passing in a number of milliseconds as a parameter to `takeLastWithTime`. 


 Note that the mechanism by which this is implemented will delay the emission of any item from the source Observable until that Observable completes. 


 `takeLastWithTime` by default operates the timer on the `timeout` [Scheduler](../scheduler) and emits items on the `currentThread` Scheduler, but you may also pass in Schedulers of your choosing to override these, as an optional second and third parameters, respectively. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .take(10)
    .takeLastWithTime(5000);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 5
Next: 6
Next: 7
Next: 8
Next: 9
Completed
```
  `takeLastWithTime` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

    ![takeLastBuffer](http://reactivex.io/documentation/operators/images/takeLastBuffer.png)  There is also an operator called `takeLastBuffer`. It differs in behavior from `takeLast` by emitting its items not individually but collected into a single array of items that is emitted as a single item. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 5)
    .takeLastBuffer(3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 2,3,4
Completed
```
  `takeLastBuffer` is found in each of the following distributions: 


* `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![takeLastBufferWithTime](http://reactivex.io/documentation/operators/images/takeLastBufferWithTime.png)  `takeLastBuffer` also has its duration-based variant, `takeLastBufferWithTime`, which is similar to `takeLastWithTime` except that it emits its items not individually but collected into a single array of items that is emitted as a single item. 

 #### Sample Code

 
```
var source = Rx.Observable
    .timer(0, 1000)
    .take(10)
    .takeLastBufferWithTime(5000);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 5,6,7,8,9
Completed
```
  `takeLastBufferWithTime` is found in each of the following distributions: 


* `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.time.js` (requires `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `takeLast`

       RxPHP implements this operator as `takeLast`. 

  Returns a specified number of contiguous elements from the end of an observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/takeLast.php

$source = \Rx\Observable::range(0, 5)
    ->takeLast(3);

$source->subscribe($stdoutObserver);
```
  
```
Next value: 2
Next value: 3
Next value: 4
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/takelast.html>

Timeout
=======

 
> mirror the source Observable, but issue an error notification if a particular period of time elapses without any emitted items

  ![Timeout](http://reactivex.io/documentation/operators/images/timeout.c.png)  The Timeout operator allows you to abort an Observable with an `onError` termination if that Observable fails to emit any items during a specified span of time. 

  #### See Also

 * [Debounce](debounce)
* [Introduction to Rx: Timeout](http://www.introtorx.com/Content/v1.0.10621.0/13_TimeShiftedSequences.html#Timeout)
* [101 Rx Samples: Timeout — Simple](http://rxwiki.wikidot.com/101samples#toc33)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `timeout`

     RxGroovy implements this operator as `timeout`, but in several variants. 

  ![timeout](http://reactivex.io/documentation/operators/images/timeout.1.png)  The first variant accepts parameters that define a duration of time (a quantity of time, and a `TimeUnit` that this quantity is denominated in). Each time the source Observable emits an item, `timeout` starts a timer, and if that timer exceeds the duration before the source Observable emits another item, `timeout` terminates its Observable with an error (`TimeoutException`). 


 By default this variant of `timeout` operates on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `timeout` 

 * Javadoc: [`timeout(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`timeout()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout.2.png)  A second variant of `timeout` differs from the first in that instead of issuing an error notification in case of a timeout condition, it instead immediately switches to a backup Observable that you specify. 


 By default this variant of `timeout` operates on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `timeout` 

 * Javadoc: [`timeout(long,TimeUnit,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit,%20rx.Observable))
* Javadoc: [`timeout(long,TimeUnit,Observable,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit,%20rx.Observable,%20rx.Scheduler))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout3.png)  A third variant of `timeout` does not use a constant timeout duration, but sets its timeout duration on a per-item basis by passing each item from the source Observable into a function that returns an Observable and then monitoring those Observables. If any such Observable completes before the source Observable emits another item, this is considered a timeout condition, and triggers an `onError` notification (“`TimeoutException`”) from the Observable `timeout` returns. 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func1))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout4.png)  There is also a variant of `timeout` that both uses a per-item Observable to set the timeout duration and switches to a backup Observable in case of a timeout. 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func1,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func1,%20rx.Observable))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout5.png)  The variant of `timeout` that uses a per-item Observable to set the timeout has a variant that allows you to pass in a function that returns an Observable that acts as a timeout timer for the very first item emitted by the source Observable (in the absence of this, there would be no timeout for the first item). 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func0,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func0,%20rx.functions.Func1))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout6.png)  And that variant also has a cousin that will switch to a specified backup Observable rather than emitting an error upon hitting a timeout condition. 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func0,Func1,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func0,%20rx.functions.Func1,%20rx.Observable))
       ###  RxJava 1․x `timeout`

     RxJava implements this operator as `timeout`, but in several variants. 

  ![timeout](http://reactivex.io/documentation/operators/images/timeout.1.png)  The first variant accepts parameters that define a duration of time (a quantity of time, and a `TimeUnit` that this quantity is denominated in). Each time the source Observable emits an item, `timeout` starts a timer, and if that timer exceeds the duration before the source Observable emits another item, `timeout` terminates its Observable with an error (`TimeoutException`). 


 By default this variant of `timeout` operates on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `timeout` 

 * Javadoc: [`timeout(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`timeout()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout.2.png)  A second variant of `timeout` differs from the first in that instead of issuing an error notification in case of a timeout condition, it instead immediately switches to a backup Observable that you specify. 


 By default this variant of `timeout` operates on the `computation` [Scheduler](../scheduler), but you can choose a different Scheduler by passing it in as an optional third parameter to `timeout`. 

 * Javadoc: [`timeout(long,TimeUnit,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit,%20rx.Observable))
* Javadoc: [`timeout(long,TimeUnit,Observable,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(long,%20java.util.concurrent.TimeUnit,%20rx.Observable,%20rx.Scheduler))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout3.png)  A third variant of `timeout` does not use a constant timeout duration, but sets its timeout duration on a per-item basis by passing each item from the source Observable into a function that returns an Observable and then monitoring those Observables. If any such Observable completes before the source Observable emits another item, this is considered a timeout condition, and triggers an `onError` notification (“`TimeoutException`”) from the Observable `timeout` returns. 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func1))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout4.png)  There is also a variant of `timeout` that both uses a per-item Observable to set the timeout duration and switches to a backup Observable in case of a timeout. 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func1,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func1,%20rx.Observable))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout5.png)  The variant of `timeout` that uses a per-item Observable to set the timeout has a variant that allows you to pass in a function that returns an Observable that acts as a timeout timer for the very first item emitted by the source Observable (in the absence of this, there would be no timeout for the first item). 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func0,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func0,%20rx.functions.Func1))
   ![timeout](http://reactivex.io/documentation/operators/images/timeout6.png)  And that variant also has a cousin that will switch to a specified backup Observable rather than emitting an error upon hitting a timeout condition. 


 This variant of `timeout` by default runs on the `immediate` [Scheduler](../scheduler). 

 * Javadoc: [`timeout(Func0,Func1,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#timeout(rx.functions.Func0,%20rx.functions.Func1,%20rx.Observable))
       ###  RxJS `timeout timeoutWithSelector`

     RxJS implements this operator as `timeout` and `timeoutWithSelector`: 

  ![timeout](http://reactivex.io/documentation/operators/images/timeout.1.png)  One variant of `timeout` accepts a duration of time (in milliseconds). Each time the source Observable emits an item, `timeout` starts a timer, and if that timer exceeds the duration before the source Observable emits another item, `timeout` terminates its Observable with an error (“`Timeout`” or a string of your choice that you pass as an optional second parameter). 

 #### Sample Code

 
```
var source = Rx.Observable
    .return(42)
    .delay(5000)
    .timeout(200, 'Timeout has occurred.');

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Error: Timeout has occurred.
```
   ![timeout](http://reactivex.io/documentation/operators/images/timeout.2.png)  Another variant allows you to instruct `timeout` to switch to a backup Observable that you specify, rather than terminating with an error, if the timeout condition is triggered. To use this variant, pass the backup Observable (or `Promise`) as the second parameter to `timeout`. 

 #### Sample Code

 
```
var source = Rx.Observable
  .return(42)
  .delay(5000)
  .timeout(200, Promise.resolve(42));

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: 42
Completed
```
   ![timeoutWithSelector](http://reactivex.io/documentation/operators/images/timeoutWithSelector3.png)  `timeoutWithSelector` does not use a constant timeout duration, but sets its timeout duration on a per-item basis by passing each item from the source Observable into a function that returns an Observable and then monitoring those Observables. If any such Observable completes before the source Observable emits another item, this is considered a timeout condition, and triggers an `onError` notification (“`Error: Timeout`”) from the Observable `timeoutWithSelector` returns. 

 #### Sample Code

 
```
var array = [
    200,
    300,
    350,
    400
];

var source = Rx.Observable
    .for(array, function (x) {
        return Rx.Observable.timer(x);
    })
    .map(function (x, i) { return i; })
    .timeoutWithSelector(function (x) {
        return Rx.Observable.timer(400);
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Error: Error: Timeout
```
    ![timeoutWithSelector](http://reactivex.io/documentation/operators/images/timeoutWithSelector4.png)  There is also a variant of `timeoutWithSelector` that both uses a per-item Observable to set the timeout duration and switches to a backup Observable in case of a timeout. 

 #### Sample Code

 
```
var array = [
    200,
    300,
    350,
    400
];

var source = Rx.Observable
    .for(array, function (x) {
        return Rx.Observable.timer(x);
    })
    .map(function (x, i) { return i; })
    .timeoutWithSelector(function (x) {
        return Rx.Observable.timer(400);
    }, Rx.Observable.return(42));

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Next: 42
Completed
```
    ![timeoutWithSelector](http://reactivex.io/documentation/operators/images/timeoutWithSelector5.png)  The variant of `timeoutWithSelector` that uses a per-item Observable to set the timeout has a variant that allows you to pass in an Observable that acts as a timeout timer for the very first item emitted by the source Observable (in the absence of this, there would be no timeout for the first item; that is to say, the default Observable that governs this first timeout period is `Rx.Observable.never()`). 

 #### Sample Code

 
```
var array = [
    200,
    300,
    350,
    400
];

var source = Rx.Observable
    .for(array, function (x) {
        return Rx.Observable.timer(x);
    })
    .map(function (x, i) { return i; })
    .timeoutWithSelector(Rx.Observable.timer(250), function (x) {
        return Rx.Observable.timer(400);
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Error: Error: Timeout
```
    ![timeoutWithSelector](http://reactivex.io/documentation/operators/images/timeoutWithSelector6.png)  And that variant also has a cousin that will switch to a specified backup Observable rather than emitting an error upon hitting a timeout condition. 

 #### Sample Code

 
```
var array = [
    200,
    300,
    350,
    400
];

var source = Rx.Observable
    .for(array, function (x) {
        return Rx.Observable.timer(x);
    })
    .map(function (x, i) { return i; })
    .timeoutWithSelector(Rx.Observable.timer(250), function (x) {
        return Rx.Observable.timer(400);
    }, Rx.Observable.return(42));

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Next: 42
Completed
```
    `timeout` and `timeoutWithSelector` are found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.time.js`
* `rx.lite.js`
* `rx.lite.compat.js`

  They require one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `timeout`

       RxPHP implements this operator as `timeout`. 

  Errors the observable sequence if no item is emitted in the specified time. When a timeout occurs, this operator errors with an instance of Rx\Exception\TimeoutException 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/timeout/timeout.php

Rx\Observable::interval(1000)
    ->timeout(500)
    ->subscribe($createStdoutObserver('One second - '));

Rx\Observable::interval(100)
    ->take(3)
    ->timeout(500)
    ->subscribe($createStdoutObserver('100 ms     - '));
```
  
```
100 ms     - Next value: 0
100 ms     - Next value: 1
100 ms     - Next value: 2
100 ms     - Complete!
One second - Exception: timeout
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/timeout.html>

Publish
=======

 
> convert an ordinary Observable into a connectable Observable

  ![Publish](http://reactivex.io/documentation/operators/images/publishConnect.c.png)  A connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when the Connect operator is applied to it. In this way you can prompt an Observable to begin emitting items at a time of your choosing. 

  #### See Also

 * [Connect](connect)
* [RefCount](refcount)
* [Replay](replay)
* [Introduction to Rx: Publish & Connect](http://www.introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html#PublishAndConnect)
* [101 Rx Samples: Publish — Sharing a subscription with multiple Observers](http://rxwiki.wikidot.com/101samples#toc48)
* [Wedding Party: Share, Publish, Refcount, and All That Jazz](http://blog.kaush.co/2015/01/21/rxjava-tip-for-the-day-share-publish-refcount-and-all-that-jazz/) by Kaushik Gopal

 Language-Specific Information
-----------------------------

    ###  RxGroovy `publish`

     ![publish](http://reactivex.io/documentation/operators/images/publishConnect.png)  RxGroovy implements this operator as `publish`. 

 * Javadoc: [`publish()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#publish())
   ![publish](http://reactivex.io/documentation/operators/images/publishConnect.f.png)  There is also a variant that takes a function as a parameter. This function takes an emitted item from the source Observable as a parameter and produces the item that will be emitted in its place by the resulting Observable. 

 * Javadoc: [`publish(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#publish(rx.functions.Func1))
       ###  RxJava 1․x `publish`

     ![publish](http://reactivex.io/documentation/operators/images/publishConnect.png)  RxJava implements this operator as `publish`. 

 * Javadoc: [`publish()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#publish())
   ![publish](http://reactivex.io/documentation/operators/images/publishConnect.f.png)  There is also a variant that takes a function as a parameter. This function takes as a parameter the `ConnectableObservable` that shares a single subscription to the underlying Observable sequence. This function produces and returns a new Observable sequence. 

 * Javadoc: [`publish(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#publish(rx.functions.Func1))
       ###  RxJS `let letBind multicast publish publishLast publishValue`

     ![publish](http://reactivex.io/documentation/operators/images/publishConnect.f.png)  In RxJS, the `publish` operator takes a function as a parameter. This function takes an emitted item from the source Observable as a parameter and produces the item that will be emitted in its place by the returned `ConnectableObservable`. 

 #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(2)
    .doAction(function (x) {
        console.log('Side effect');
    });

var published = source.publish();

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

var connection = published.connect();

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Side effect
Next: SourceA0
Next: SourceB0
Side effect
Next: SourceA1
Next: SourceB1
Completed
```
    ![publishValue](http://reactivex.io/documentation/operators/images/publishValue.png)  The `publishValue` operator takes, in addition to the function described above, an initial item to be emitted by the resulting `ConnectableObservable` at connection time before emitting the items from the source Observable. It will not, however, emit this initial item to observers that subscribe after the time of connection. 

 #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(2)
    .doAction(function (x) {
        console.log('Side effect');
    });

var published = source.publishValue(42);

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

var connection = published.connect();

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Next: SourceA42
Next: SourceB42
Side effect
Next: SourceA0
Next: SourceB0
Side effect
Next: SourceA1
Next: SourceB1
Completed
Completed
```
    ![publishLast](http://reactivex.io/documentation/operators/images/publishLast.png)  The `publishLast` operator is similar to `publish`, and takes a similarly-behaving function as its parameter. It differs from `publish` in that instead of applying that function to, and emitting an item for *every* item emitted by the source Observable subsequent to the connection, it only applies that function to and emits an item for the *last* item that was emitted by the source Observable, when that source Observable terminates normally. 

 #### Sample Code

 
```
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(2)
    .doAction(function (x) {
        console.log('Side effect');
    });

var published = source.publishLast();

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

var connection = published.connect();

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) { console.log('Next: ' + tag + x); },
        function (err) { console.log('Error: ' + err); },
        function () { console.log('Completed'); });
}
```


```
Side effect
Side effect
Next: SourceA1
Completed
Next: SourceB1
Completed
```
    The above operators are available in the following packages: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.binding.js` (requires either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

  RxJS also has a `multicast` operator which operates on an ordinary Observable, multicasts that Observable by means of a particular Subject that you specify, applies a transformative function to each emission, and then emits those transformed values as its own ordinary Observable sequence. Each subscription to this new Observable will trigger a new subscription to the underlying multicast Observable. 

 #### Sample Code

 
```
var subject = new Rx.Subject();
var source = Rx.Observable.range(0, 3)
    .multicast(subject);

var observer = Rx.Observer.create(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); }
);

var subscription = source.subscribe(observer);
subject.subscribe(observer);

var connected = source.connect();

subscription.dispose();
```


```
Next: 0
Next: 0
Next: 1
Next: 1
Next: 2
Next: 2
Completed
```
  The `multicast` operator is available in the following packages: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.binding.js` (requires either `rx.lite.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

  There is also a `let` operator (the alias `letBind` is available for browsers such as Internet Explorer before IE9 where “`let`” is forbidden). It is similar to `multicast` but does not multicast the underlying Observable through a Subject: 

 #### Sample Code

 
```
var obs = Rx.Observable.range(1, 3);

var source = obs.let(function (o) { return o.concat(o); });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 1
Next: 2
Next: 3
Next: 1
Next: 2
Next: 3
Completed
```
  The `let` (or `letBind`) operator is available in the following packages: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.experimental.js`

  It requires one of the following packages: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `multicast multicastWithSelector publish publishLast publishValue`

       RxPHP implements this operator as `multicast`. 

  Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/multicast/multicast.php

$subject = new \Rx\Subject\Subject();
$source  = \Rx\Observable::range(0, 3)->multicast($subject);

$subscription = $source->subscribe($stdoutObserver);
$subject->subscribe($stdoutObserver);

$connected = $source->connect();
```
  
```
Next value: 0
Next value: 0
Next value: 1
Next value: 1
Next value: 2
Next value: 2
Complete!
```
      RxPHP also has an operator `multicastWithSelector`. 

  Multicasts the source sequence notifications through an instantiated subject from a subject selector factory, into all uses of the sequence within a selector function. Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. 

     RxPHP also has an operator `publish`. 

  Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. This operator is a specialization of Multicast using a regular Subject. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/publish/publish.php

/* With publish */
$interval = \Rx\Observable::range(0, 10);

$source = $interval
    ->take(2)
    ->doOnNext(function ($x) {
        echo "Side effect\n";
    });

$published = $source->publish();

$published->subscribe($createStdoutObserver('SourceC '));
$published->subscribe($createStdoutObserver('SourceD '));

$published->connect();
```
  
```
Side effect
SourceC Next value: 0
SourceD Next value: 0
Side effect
SourceC Next value: 1
SourceD Next value: 1
SourceC Complete!
SourceD Complete!
```
      RxPHP also has an operator `publishLast`. 

  Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. This operator is a specialization of Multicast using a AsyncSubject. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/publish/publishLast.php

$range = \Rx\Observable::fromArray(range(0, 1000));

$source = $range
    ->take(2)
    ->doOnNext(function ($x) {
        echo "Side effect\n";
    });

$published = $source->publishLast();

$published->subscribe($createStdoutObserver('SourceA'));
$published->subscribe($createStdoutObserver('SourceB'));

$connection = $published->connect();
```
  
```
Side effect
Side effect
SourceANext value: 1
SourceBNext value: 1
SourceAComplete!
SourceBComplete!
```
      RxPHP also has an operator `publishValue`. 

  Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. This operator is a specialization of Multicast using a BehaviorSubject. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/publish/publishValue.php

$range = \Rx\Observable::fromArray(range(0, 1000));

$source = $range
    ->take(2)
    ->doOnNext(function ($x) {
        echo "Side effect\n";
    });

$published = $source->publishValue(42);

$published->subscribe($createStdoutObserver('SourceA'));
$published->subscribe($createStdoutObserver('SourceB'));

$connection = $published->connect();
```
  
```
SourceANext value: 42
SourceBNext value: 42
Side effect
SourceANext value: 0
SourceBNext value: 0
Side effect
SourceANext value: 1
SourceBNext value: 1
SourceAComplete!
SourceBComplete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/publish.html>

Zip
===

 
> combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#zip)  The `Zip` method returns an Observable that applies a function of your choosing to the combination of items emitted, in sequence, by two (or more) other Observables, with the results of this function becoming the items emitted by the returned Observable. It applies this function in strict sequence, so the first item emitted by the new Observable will be the result of the function applied to the first item emitted by Observable #1 and the first item emitted by Observable #2; the second item emitted by the new zip-Observable will be the result of the function applied to the second item emitted by Observable #1 and the second item emitted by Observable #2; and so forth. It will only emit as many items as the number of items emitted by the source Observable that emits the fewest items. 

  #### See Also

 * [And/Then/When](and-then-when)
* [CombineLatest](combinelatest)
* [Introduction to Rx: Zip](http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#Zip)
* [RxMarbles: `zip`](http://rxmarbles.com/#zip)
* [101 Rx Samples: Zip](http://rxwiki.wikidot.com/101samples#toc49)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `zip zipWith`

     RxGroovy implements this operator as several variants of `zip` and also as `zipWith`, an instance function version of the operator. 

  ![zip](http://reactivex.io/documentation/operators/images/zip.o.png)  The last argument to `zip` is a function that accepts an item from each of the Observables being zipped and emits an item to be emitted in response by the Observable returned from `zip`. You can provide the Observables to be zipped together to `zip` either as between two and nine individual parameters, or as a single parameter: either an Iterable of Observables or an Observable that emits Observables (as in the illustration above). 

 #### Sample Code

 
```
odds  = Observable.from([1, 3, 5, 7, 9]);
evens = Observable.from([2, 4, 6]);

Observable.zip(odds, evens, {o, e -> [o, e]}).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
[1, 2]
[3, 4]
[5, 6]
Sequence complete
```
  Note that in this example, the resulting Observable completes normally after emitting three items, which is the number of items emitted by the shorter of the two component Observbles (`evens`, which emits three items). 

 * Javadoc: [`zip(Iterable<Observable>,FuncN)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zip(java.lang.Iterable,%20rx.functions.FuncN))
* Javadoc: [`zip(Observable<Observable>,FuncN)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zip(rx.Observable,%20rx.functions.FuncN))
* Javadoc: [`zip(Observable,Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zip(rx.Observable,%20rx.Observable,%20rx.functions.Func2)) (there are also versions that take up to nine Observables)
   ![zipWith](http://reactivex.io/documentation/operators/images/zip.i.png)  The `zipWith` instance version of this operator always takes two parameters. The first parameter may be either a simple Observable, or an iterable (as in the illustration above). 

 * Javadoc: [`zipWith(Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zipWith(rx.Observable,%20rx.functions.Func2))
* Javadoc: [`zipWith(Iterable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zipWith(java.lang.Iterable,%20rx.functions.Func2))
   `zip` and `zipWith` do not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJava 1․x `zip zipWith`

     RxJava implements this operator as several variants of `zip` and also as `zipWith`, an instance function version of the operator. 

  ![zip](http://reactivex.io/documentation/operators/images/zip.o.png)  The last argument to `zip` is a function that accepts an item from each of the Observables being zipped and emits an item to be emitted in response by the Observable returned from `zip`. You can provide the Observables to be zipped together to `zip` either as between two and nine individual parameters, or as a single parameter: either an Iterable of Observables or an Observable that emits Observables (as in the illustration above). 

 * Javadoc: [`zip(Iterable<Observable>,FuncN)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zip(java.lang.Iterable,%20rx.functions.FuncN))
* Javadoc: [`zip(Observable<Observable>,FuncN)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zip(rx.Observable,%20rx.functions.FuncN))
* Javadoc: [`zip(Observable,Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zip(rx.Observable,%20rx.Observable,%20rx.functions.Func2)) (there are also versions that take up to nine Observables)
   ![zipWith](http://reactivex.io/documentation/operators/images/zip.i.png)  The `zipWith` instance version of this operator always takes two parameters. The first parameter may be either a simple Observable, or an iterable (as in the illustration above). 

 * Javadoc: [`zipWith(Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zipWith(rx.Observable,%20rx.functions.Func2))
* Javadoc: [`zipWith(Iterable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#zipWith(java.lang.Iterable,%20rx.functions.Func2))
   `zip` and `zipWith` do not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJS `forkJoin zip zipArray`

     RxJS implements this operator as `zip` and `zipArray`. 

  ![zip](http://reactivex.io/documentation/operators/images/zip.png)  `zip` accepts a variable number of Observables or Promises as parameters, followed by a function that accepts one item emitted by each of those Observables or resolved by those Promises as input and produces a single item to be emitted by the resulting Observable. 

 #### Sample Code

 
```
/* Using arguments */
var range = Rx.Observable.range(0, 5);

var source = Observable.zip(
    range,
    range.skip(1),
    range.skip(2),
    function (s1, s2, s3) {
        return s1 + ':' + s2 + ':' + s3;
    }
);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 0:1:2
Next: 1:2:3
Next: 2:3:4
Completed
```
 
```
/* Using promises and Observables */
var range = Rx.Observable.range(0, 5);

var source = Observable.zip(
    RSVP.Promise.resolve(0),
    RSVP.Promise.resolve(1),
    Rx.Observable.return(2)
    function (s1, s2, s3) {
        return s1 + ':' + s2 + ':' + s3;
    }
);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 0:1:2
Completed
```
    ![zipArray](http://reactivex.io/documentation/operators/images/zipArray.png)  `zipArray` accepts a variable number of Observables as parameters and returns an Observable that emits arrays, each one containing the *n*th item from each source Observable. 

 #### Sample Code

 
```
var range = Rx.Observable.range(0, 5);

var source = Rx.Observable.zipArray(
    range,
    range.skip(1), 
    range.skip(2)
);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);   
    },
    function () {
        console.log('Completed');   
    });
```
 
```
Next: [0,1,2]
Next: [1,2,3]
Next: [2,3,4]
Completed
```
    ![forkJoin](http://reactivex.io/documentation/operators/images/forkJoin.png)  RxJS also implements a similar operator, `forkJoin`. There are two varieties of this operator. The first collects the last element emitted by each of the source Observables into an array and emits this array as its own sole emitted item. You can either pass a list of Observables to `forkJoin` as individual parameters or as an array of Observables. 

 
```
var source = Rx.Observable.forkJoin(
    Rx.Observable.return(42),
    Rx.Observable.range(0, 10),
    Rx.Observable.fromArray([1,2,3]),
    RSVP.Promise.resolve(56)
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: [42, 9, 3, 56]
Completed
```
    ![forkJoin](http://reactivex.io/documentation/operators/images/forkJoin.p.png) 
 A second variant of `forkJoin` exists as a prototype function, and you call it on an instance of one source Observable, passing it another source Observable as a parameter. As a second parameter, you pass it a function that combines the final item emitted by the two source Observables into the sole item to be emitted by the resulting Observable. 

 
```
var source1 = Rx.Observable.return(42);
var source2 = Rx.Observable.range(0, 3);

var source = source1.forkJoin(source2, function (s1, s2) {
    return s1 + s2;
});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 44
Completed
```
    `forkJoin` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.experimental.js` (requires `rx.js`, `rx.compat.js`, `rx.lite.js`, or `rx.lite.compat.js`)

      ###  RxPHP `zip forkJoin`

       RxPHP implements this operator as `zip`. 

  Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. If the result selector function is omitted, a list with the elements of the observable sequences at corresponding indexes will be yielded. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/zip/zip.php

//Without a result selector
$range = \Rx\Observable::fromArray(range(0, 4));

$source = $range
    ->zip([
        $range->skip(1),
        $range->skip(2)
    ]);

$observer = $createStdoutObserver();

$subscription = $source
    ->subscribe(new CallbackObserver(
        function ($array) use ($observer) {
            $observer->onNext(json_encode($array));
        },
        [$observer, 'onError'],
        [$observer, 'onCompleted']
    ));
```
  
```
Next value: [0,1,2]
Next value: [1,2,3]
Next value: [2,3,4]
Complete!
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/zip/zip-result-selector.php

//With a result selector
$range = \Rx\Observable::fromArray(range(0, 4));

$source = $range
    ->zip([
        $range->skip(1),
        $range->skip(2)
    ], function ($s1, $s2, $s3) {
        return $s1 . ':' . $s2 . ':' . $s3;
    });

$observer = $createStdoutObserver();

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 0:1:2
Next value: 1:2:3
Next value: 2:3:4
Complete!
```
      RxPHP also has an operator `forkJoin`. 

  Runs all observable sequences in parallel and collect their last elements. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/forkJoin/forkJoin.php

use Rx\Observable;

$obs1 = Observable::range(1, 4);
$obs2 = Observable::range(3, 5);
$obs3 = Observable::fromArray(['a', 'b', 'c']);

$observable = Observable::forkJoin([$obs1, $obs2, $obs3], function($v1, $v2, $v3) {
    return $v1 . $v2 . $v3;
});
$observable->subscribe($stdoutObserver);
```
  
```
Next value: 47c
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/zip.html>

Defer
=====

 
> do not create the Observable until the observer subscribes, and create a fresh Observable for each observer

  ![Defer](http://reactivex.io/documentation/operators/images/defer.c.png)  The Defer operator waits until an observer subscribes to it, and then it generates an Observable, typically with an Observable factory function. It does this afresh for each subscriber, so although each subscriber may think it is subscribing to the same Observable, in fact each subscriber gets its own individual sequence. 


 In some circumstances, waiting until the last minute (that is, until subscription time) to generate the Observable can ensure that this Observable contains the freshest data. 

  #### See Also:

 * [Deferring Observable code until subscription in RxJava](http://blog.danlew.net/2015/07/23/deferring-observable-code-until-subscription-in-rxjava/) by Dan Lew

 Language-Specific Information
-----------------------------

    ###  RxGroovy `defer ifThen switchCase`

     ![defer](http://reactivex.io/documentation/operators/images/defer.png)  RxGroovy implements this operator as `defer`. This operator takes as its sole parameter an Observable factory function of your choosing. This function takes no parameters and returns an Observable. 


 `defer` does not by default operate on a particular [Scheduler](../scheduler). 

 * Javadoc: [`defer()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#defer(rx.functions.Func0))
   ![switchCase](http://reactivex.io/documentation/operators/images/switchCase.png)  There is a somewhat similar operator in the optional `rxjava-computation-expressions` package (it is not part of the standard RxGroovy set of operators). The `switchCase` operator conditionally creates and returns one of a set of possible Observables. 

   ![ifThen](http://reactivex.io/documentation/operators/images/ifThen.png)  An even simpler operator in the optional `rxjava-computation-expressions` package (also not part of the standard RxGroovy set of operators) is `ifThen`. This operator checks a condition and then either mirrors the source Observable or an empty Observable depending on the result. 

       ###  RxJava 1․x `defer ifThen switchCase`

     ![defer](http://reactivex.io/documentation/operators/images/defer.png)  RxJava implements this operator as `defer`. This operator takes as its sole parameter an Observable factory function of your choosing. This function takes no parameters and returns an Observable. 


 `defer` does not by default operate on a particular [Scheduler](../scheduler). 

 * Javadoc: [`defer()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#defer(rx.functions.Func0))
   ![switchCase](http://reactivex.io/documentation/operators/images/switchCase.png)  There is a somewhat similar operator in the optional `rxjava-computation-expressions` package (it is not part of the standard RxJava set of operators). The `switchCase` operator conditionally creates and returns one of a set of possible Observables. 

   ![ifThen](http://reactivex.io/documentation/operators/images/ifThen.png)  An even simpler operator in the optional `rxjava-computation-expressions` package (also not part of the standard RxGroovy set of operators) is `ifThen`. This operator checks a condition and then either mirrors the source Observable or an empty Observable depending on the result. 

       ###  RxJS `case defer if switchCase`

     ![defer](http://reactivex.io/documentation/operators/images/defer.png)  RxJS implements this operator as `defer`. This operator takes as its sole parameter an Observable factory function of your choosing. This function takes no parameters and returns an Observable or a Promise. 

 #### Sample Code

 
```
/* Using an observable sequence */
var source = Rx.Observable.defer(function () {
    return Rx.Observable.return(42);
});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); } );
```
 
```
Next: 42
Completed
```
 
```
var source = Rx.Observable.defer(function () {
    return RSVP.Promise.resolve(42);
});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); } );
```
 
```
Next: 42
Completed
```
  `defer` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![if](http://reactivex.io/documentation/operators/images/if.png)  RxJS also implements the `if` operator. It takes as parameters a function that returns a boolean, an Observable to mirror if that function returns a true value, and optionally a second Observable to mirror if that function returns a false value (if you omit this parameter, `if` will mirror an empty Observable in such a case). 


#### Sample Code

 
```
var shouldRun = false;

var source = Rx.Observable.if(
    function () { return shouldRun; },
    Rx.Observable.return(42),
    Rx.Observable.return(56)
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 56
Completed
```
  `if` is found in the following distributions: 

 * `rx.all.js`
* `rx.experimental.js` (requires `rx.js`, `rx.compat.js`, `rx.lite.js`, or `rx.lite.compat.js`)

    ![case](http://reactivex.io/documentation/operators/images/case.png)  RxJS implements a somewhat similar operator called `case` (or “`switchCase`”). This operator conditionally creates and returns one of a set of possible Observables. It takes the following parameters: 

 1. a function that returns the key that determines which Observable to emit
2. an object that associates those keys with particular Observables
3. (optional) a [Scheduler](../scheduler) or an Observable: Scheduler the Scheduler you want this operator to use Observable the default Observable to emit if the key does not associate with any Observables

 #### Sample Code

 
```
var sources = {
    'foo': Rx.Observable.return(42),
    'bar': Rx.Observable.return(56)
};

var defaultSource = Rx.Observable.empty();

var source = Rx.Observable.case(
    function () {
        return 'foo';
    },
    sources,
    defaultSource);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); } );
```
 
```
Next: 42
Completed
```
  `case`/`switchCase` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.experimental.js` (requires `rx.js`, `rx.compat.js`, `rx.lite.js`, or `rx.lite.compat.js`)

        ###  RxPHP `defer`

       RxPHP implements this operator as `defer`. 

  Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/defer/defer.php


$source = \Rx\Observable::defer(function () {
    return \Rx\Observable::of(42);
});

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/defer.html>

Empty
=====

 
> create an Observable that emits no items but terminates normally

  ![Empty](http://reactivex.io/documentation/operators/images/empty.c.png)  Never
-----

 ### create an Observable that emits no items and does not terminate

  ![Never](http://reactivex.io/documentation/operators/images/never.c.png)  Throw
-----

 ### create an Observable that emits no items and terminates with an error

  ![Throw](http://reactivex.io/documentation/operators/images/throw.c.png)   The Empty, Never, and Throw operators generate Observables with very specific and limited behavior. These are useful for testing purposes, and sometimes also for combining with other Observables or as parameters to operators that expect other Observables as parameters. 

 #### See Also

 * [Introduction to Rx: Simple Factory Methods](http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#SimpleFactoryMethods)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `empty never error`

     RxGroovy implements these operators as `empty`, `never`, and `error`. The `error` operator takes as a parameter the `Throwable` with which you want the Observable to terminate. 


 These operators do not operate by default on any particular [Scheduler](../scheduler), but `empty` and `error` optionally take a Scheduler as a parameter, and if you pass them a Scheduler they will issue their termination notifications on that Scheduler. 

 #### Sample Code

 
```
println("*** empty() ***");
Observable.empty().subscribe(
  { println("empty: " + it); },                      // onNext
  { println("empty: error - " + it.getMessage()); }, // onError
  { println("empty: Sequence complete"); }           // onCompleted
);

println("*** error() ***");
Observable.error(new Throwable("badness")).subscribe(
  { println("error: " + it); },                      // onNext
  { println("error: error - " + it.getMessage()); }, // onError
  { println("error: Sequence complete"); }           // onCompleted
);

println("*** never() ***");
Observable.never().subscribe(
  { println("never: " + it); },                      // onNext
  { println("never: error - " + it.getMessage()); }, // onError
  { println("never: Sequence complete"); }           // onCompleted
);
println("*** END ***");
```
 
```
*** empty() ***
empty: Sequence complete
*** error() ***
error: error - badness
*** never() ***
*** END ***
```
 * Javadoc: [`empty()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#empty())
* Javadoc: [`never()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#never())
* Javadoc: [`error(throwable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#error(java.lang.Throwable))

      ###  RxJava 1․x `empty never error`

     RxJava 1.x implements these operators as `empty`, `never`, and `error`. The `error` operator takes as a parameter the `Throwable` with which you want the Observable to terminate. 


 These operators do not operate by default on any particular [Scheduler](../scheduler), but `empty` and `error` optionally take a Scheduler as a parameter, and if you pass them a Scheduler they will issue their termination notifications on that Scheduler. 

 * Javadoc: [`empty()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#empty())
* Javadoc: [`never()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#never())
* Javadoc: [`error(throwable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#error(java.lang.Throwable))

      ###  RxJava 2․x `empty never error`

     RxJava 2.x implements these operators as `empty`, `never`, and `error`. The `error` operator takes as a parameter the `Throwable` with which you want the Observable to terminate, or a `Callable` that returns such a `Throwable`. 


 These operators do not operate by default on any particular [Scheduler](../scheduler). 

 * Javadoc: [`empty()`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html#empty())
* Javadoc: [`never()`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html#never())
* Javadoc: [`error(Callable)`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html#error(java.util.concurrent.Callable))
* Javadoc: [`error(Throwable)`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html#error(java.lang.Throwable))

      ###  RxJS `empty never throw`

     RxJS implements these operators as `empty`, `never`, and `throw`. 

 #### Sample Code

 
```
var source = Rx.Observable.empty();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Completed
```
 
```
// This will never produce a value, hence never calling any of the callbacks
var source = Rx.Observable.never();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
var source = Rx.Observable.return(42)
    .selectMany(Rx.Observable.throw(new Error('error!')));

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Error: Error: error!
```
  `empty` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

  `never` is found in the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

  `throw` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `empty never error`

       RxPHP implements this operator as `empty`. 

  Returns an empty observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/empty/empty.php

$observable = \Rx\Observable::empty();
$observable->subscribe($stdoutObserver);
```
  
```
Complete!
```
      RxPHP also has an operator `never`. 

  Returns a non-terminating observable sequence, which can be used to denote an infinite duration. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/never/never.php

$observable = \Rx\Observable::never();
$observable->subscribe($stdoutObserver);
```
     RxPHP also has an operator `error`. 

  Returns an observable sequence that terminates with an exception. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/error-observable/error-observable.php

$observable = Rx\Observable::error(new Exception('Oops!'));
$observable->subscribe($stdoutObserver);
```
  
```
Exception: Oops!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/empty-never-throw.html>

Just
====

 
> create an Observable that emits a particular item

  ![Just](http://reactivex.io/documentation/operators/images/just.c.png)  The Just operator converts an item into an Observable that emits that item. 


 Just is similar to From, but note that From will dive into an array or an iterable or something of that sort to pull out items to emit, while Just will simply emit the array or iterable or what-have-you as it is, unchanged, as a single item. 


 Note that if you pass `null` to Just, it will return an Observable that *emits* `null` as an item. Do not make the mistake of assuming that this will return an empty Observable (one that emits no items at all). For that, you will need the [Empty](empty-never-throw) operator. 

  #### See Also

 * [From](from)
* [Repeat](repeat)
* [Start](start)
* [Timer](timer)
* [Introduction to Rx: Return](http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableReturn)
* [RxJava Tutorial 03: Observable from, just, & create methods](https://www.youtube.com/watch?v=sDqrlNprY24)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `just`

     ![just](http://reactivex.io/documentation/operators/images/just.png)  RxGroovy implements this operator as `just`. It accepts between one and nine items as parameters, and returns an Observable that emits these items in the same order as they are given in the parameter list. 


 `just` does not by default operate on any particular [Scheduler](../scheduler). 

 #### Sample Code

 
```
// Observable emits "some string" as a single item
def observableThatEmitsAString = Observable.just("some string"); 
// Observable emits the list [1, 2, 3, 4, 5] as a single item
def observableThatEmitsAList = Observable.just([1, 2, 3, 4, 5]); 
// Observable emits 1, 2, 3, 4, and 5 as distinct items
def observableThatEmitsSeveralNumbers = Observable.just( 1, 2, 3, 4, 5 );
```
 * Javadoc: [`just(item)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#just(T)) (there are also versions that accept between two and nine items as parameters)
       ###  RxJava 1․x `just`

     ![just](http://reactivex.io/documentation/operators/images/just.png)  RxJava implements this operator as `just`. It accepts between one and nine items as parameters, and returns an Observable that emits these items in the same order as they are given in the parameter list. 


 `just` does not by default operate on any particular [Scheduler](../scheduler). 

 #### Sample Code

 
```
Observable.just(1, 2, 3)
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Next: 2
Next: 3
Sequence complete.
```
 * Javadoc: [`just(item)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#just(T)) (there are also versions that accept between two and nine items as parameters)
       ###  RxJS `just return`

     ![just](http://reactivex.io/documentation/operators/images/just.png)  RxJS implements this operator as `return` and as `just` (two names for the same operator with the same behavior). It accepts a single item as a parameter and returns an Observable that emits that single item as its sole emission. 


 `return`/`just` operates by default on the `immediate` [Scheduler](../scheduler), but you can also pass in a Scheduler of your choosing as an optional second parameter, in which case it will operate on that Scheduler instead. 

 #### Sample Code

 
```
var source = Rx.Observable.just(42);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```


```
Next: 42
Completed
```
  `return`/`just` is found in each of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `of`

       RxPHP implements this operator as `of`. 

  Returns an observable sequence that contains a single element. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/of/of.php


$source =  \Rx\Observable::of(42);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Complete!
```
         ###  RxSwift `just sequenceOf`

      In Swift, this is implemented using the `Observable.just` class method. 

  The parameter, whether a tuple (i.e. `(1, 2, 3)`) or an array (i.e. `[1,2,3]`) is produced as one emission. 

 #### Sample Code

 
```
let source = Observable.just(1, 2, 3)

source.subscribe {
    print($0)
}

let source2 = Observable.just([1,2,3])

source2.subscribe {
    print($0)
}
```
  
```
next((1, 2, 3))
completed
next([1, 2, 3])
completed
```
   The difference between this and `Observable.from` is that the latter's parameter is an array or a sequence, and emits each of its element as one emission. 

     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/just.html>

Range
=====

 
> create an Observable that emits a particular range of sequential integers

  ![Range](http://reactivex.io/documentation/operators/images/range.c.png)  The Range operator emits a range of sequential integers, in order, where you select the start of the range and its length. 

  #### See Also

 * [Interval](interval)
* [Introduction to Rx: Range](http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableRange)
* [101 Rx Samples: Range](http://rxwiki.wikidot.com/101samples#toc40)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `range`

     ![range](http://reactivex.io/documentation/operators/images/range.png)  RxGroovy implements this operator as `range`. It accepts as its parameters the start value of the range and the number of items in the range. If you set that number of items to zero, the resulting Observable will emit no values (if you set it to a negative number, `range` will cause an exception). 


 `range` does not by default operate on any particular [Scheduler](../scheduler), but there is a variant that allows you to set the Scheduler by passing one in as a parameter. 

 #### Sample Code

 
```
// myObservable emits the integers 5, 6, and 7 before completing:
def myObservable = Observable.range(5, 3);
```
 * Javadoc: [`range(int,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#range(int,%20int))
* Javadoc: [`range(int,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#range(int,%20int%20rx.Scheduler))
       ###  RxJava 1․x `range`

     ![range](http://reactivex.io/documentation/operators/images/range.png)  RxJava implements this operator as `range`. It accepts as its parameters the start value of the range and the number of items in the range. If you set that number of items to zero, the resulting Observable will emit no values (if you set it to a negative number, `range` will cause an exception). 


 `range` does not by default operate on any particular [Scheduler](../scheduler), but there is a variant that allows you to set the Scheduler by passing one in as a parameter. 

 * Javadoc: [`range(int,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#range(int,%20int))
* Javadoc: [`range(int,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#range(int,%20int%20rx.Scheduler))
       ###  RxJS `range`

     ![range](http://reactivex.io/documentation/operators/images/range.png)  RxJS implements this operator as `range`. It accepts as its parameters the start value of the range and the number of items in the range. 


 `range` operates by default on the `currentThread` [Scheduler](../scheduler), but there is a variant that allows you to set the Scheduler by passing one in as the optional third parameter. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 0
Next: 1
Next: 2
Completed
```
  `range` is found in each of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `range`

       RxPHP implements this operator as `range`. 

  Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/range/range.php

$observable = \Rx\Observable::range(0, 3);

$observable->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 2
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/range.html>

Map
===

 
> transform the items emitted by an Observable by applying a function to each item

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#map)  The Map operator applies a function of your choosing to each item emitted by the source Observable, and returns an Observable that emits the results of these function applications. 

  #### See Also

 * [FlatMap](flatmap)
* [Introduction to Rx: Select](http://www.introtorx.com/Content/v1.0.10621.0/08_Transformation.html#Select)
* [RxMarbles: `map`](http://rxmarbles.com/#map)
* [101 Rx Samples: Select — Indexed](http://rxwiki.wikidot.com/101samples#toc22)
* [Using the map method with Observable](https://egghead.io/lessons/javascript-using-the-map-method-with-observable) by Jafar Husain (JavaScript Video Tutorial)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `byLine cast encode map`

     ![map](http://reactivex.io/documentation/operators/images/map.png)  RxGroovy implements this operator as `map`. For example, the following code maps a function that squares the incoming value onto the values in `numbers`: 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5]);

numbers.map({it * it}).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
4
9
16
25
Sequence complete
```
  This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`map(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#map(rx.functions.Func1))
   ![cast](http://reactivex.io/documentation/operators/images/cast.png)  The `cast` operator is a specialized version of Map that transforms each item from the source Observable by casting it into a particular Class before reemitting it. 


* Javadoc: [`cast(Class)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#cast(java.lang.Class))
   ![encode](http://reactivex.io/documentation/operators/images/St.encode.png)  In the `StringObservable` class that is not part of the RxGroovy core there is also a specialty mapping operator, `encode`, that transforms an Observable that emits strings into an Observable that emits byte arrays that respect character boundaries of multibyte characters in the original strings. 

   ![byLine](http://reactivex.io/documentation/operators/images/St.byLine.png)  Also in the `StringObservable` class that is not part of the RxGroovy core there is a specialty mapping operator called `byLine`, that transforms an Observable that emits strings into an Observable that emits lines of text, by buffering the strings from the source Observable until a line-feed is found in one of them. 

       ###  RxJava 1․x `byLine cast encode map`

     ![map](http://reactivex.io/documentation/operators/images/map.png)  RxJava implements this operator as `map`. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`map(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#map(rx.functions.Func1))
   ![cast](http://reactivex.io/documentation/operators/images/cast.png)  The `cast` operator is a specialized version of Map that transforms each item from the source Observable by casting it into a particular Class before reemitting it. 


* Javadoc: [`cast(Class)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#cast(java.lang.Class))
   ![encode](http://reactivex.io/documentation/operators/images/St.encode.png)  In the `StringObservable` class that is not part of the RxJava core there is also a specialty mapping operator, `encode`, that transforms an Observable that emits strings into an Observable that emits byte arrays that respect character boundaries of multibyte characters in the original strings. 

   ![byLine](http://reactivex.io/documentation/operators/images/St.byLine.png)  Also in the `StringObservable` class that is not part of the RxJava core there is a specialty mapping operator called `byLine`, that transforms an Observable that emits strings into an Observable that emits lines of text, by buffering the strings from the source Observable until a line-feed is found in one of them. 

       ###  RxJS `map pluck select`

     ![map](http://reactivex.io/documentation/operators/images/map.i.png)  RxJS implements this operator as `map` or `select` (the two are synonymous). In addition to the transforming function, you may pass this operator an optional second parameter that will become the “`this`” context in which the transforming function will execute. 


 The transforming function gets three parameters: 

 1. the emitted item
2. the index of that item in the sequence of emitted items
3. the Observable from which that item was emitted

 #### Sample Code

 
```
// Using a value
var md = Rx.Observable.fromEvent(document, 'mousedown').map(true);
var mu = Rx.Observable.fromEvent(document, 'mouseup').map(false);

// Using a function
var source = Rx.Observable.range(1, 3)
    .select(function (x, idx, obs) {
        return x * x;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 1
Next: 4
Next: 9
Completed
```
    ![pluck](http://reactivex.io/documentation/operators/images/pluck.png)  There is also an operator called `pluck` which is a simpler version of this operator. It transforms the elements emitted by the source Observable by extracting a single named property from those elements and emitting that property in their place. 

 #### Sample Code

 
```
var source = Rx.Observable
    .fromArray([
        { value: 0 },
        { value: 1 },
        { value: 2 }
    ])
    .pluck('value');

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
  `map`/`select` and `pluck` are found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

 #### See Also

 * [`Rx.helpers.pluck(property)`](http://xgrommx.github.io/rx-book/content/helpers/pluck.html) from Dennis Stoyanov’s RxJS book

      ###  RxPHP `map mapWithIndex mapTo select pluck`

       RxPHP implements this operator as `map`. 

  Takes a transforming function that operates on each element. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/map/map.php

$observable = \Rx\Observable::fromArray([21, 42]);
$observable
    ->map(function ($elem) {
        return $elem * 2;
    })
    ->subscribe($stdoutObserver);
```
  
```
Next value: 42
Next value: 84
Complete!
```
      RxPHP also has an operator `mapWithIndex`. 

  Maps operator variant that calls the map selector with the index and value 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/map/mapWithIndex.php

$subscriptions = Rx\Observable::fromArray([21, 42])
    ->mapWithIndex(function ($index, $elem) {
        return $index + $elem;
    })
    ->subscribe($stdoutObserver);
```
  
```
Next value: 21
Next value: 43
Complete!
```
      RxPHP also has an operator `mapTo`. 

  Maps every value to the same value every time 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/map/mapTo.php

$subscription = Rx\Observable::fromArray([21, 42])
    ->mapTo(1)
    ->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 1
Complete!
```
      RxPHP also has an operator `select`. 

  Alias for Map 

     RxPHP also has an operator `pluck`. 

  Returns an Observable containing the value of a specified array index (if array) or property (if object) from all elements in the Observable sequence. If a property can't be resolved the observable will error. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/pluck/pluck.php

$source = Rx\Observable::fromArray([
    (object)['value' => 0],
    (object)['value' => 1],
    (object)['value' => 2]
])
    ->pluck('value');

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 2
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/map.html>

Scan
====

 
> apply a function to each item emitted by an Observable, sequentially, and emit each successive value

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#scan)  The Scan operator applies a function to the first item emitted by the source Observable and then emits the result of that function as its own first emission. It also feeds the result of the function back into the function along with the second item emitted by the source Observable in order to generate its second emission. It continues to feed back its own subsequent emissions along with the subsequent emissions from the source Observable in order to create the rest of its sequence. 


 This sort of operator is sometimes called an “accumulator” in other contexts. 

  #### See Also

 * [Reduce](reduce)
* [Introduction to Rx: Scan](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Scan)
* [RxMarbles: `scan`](http://rxmarbles.com/#scan)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `scan`

     ![scan](http://reactivex.io/documentation/operators/images/scan.png)  RxGroovy implements this operator as `scan`. The following code, for example, takes an Observable that emits a consecutive sequence of *n* integers starting with `1` and converts it, via `scan`, into an Observable that emits the first *n* [triangular numbers](http://en.wikipedia.org/wiki/Triangular_number): 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5]);

numbers.scan({ a, b -> a+b }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
3
6
10
15
Sequence complete
```
 * Javadoc: [`scan(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#scan(rx.functions.Func2))
   ![scan](http://reactivex.io/documentation/operators/images/scanSeed.png)  There is also a variant of `scan` to which you can pass a seed value to pass to the accumulator function the first time it is called (for the first emission from the source Observable) in place of the result from the missing prior call to the accumulator. Note that if you use this version, `scan` will emit this seed value as its own initial emission. Note also that passing a seed of `null` is *not* the same as passing no seed at all. A `null` seed is a valid variety of seed. 

 * Javadoc: [`scan(R,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#scan(R,%20rx.functions.Func2))
   This operator does not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJava 1․x `scan`

     ![scan](http://reactivex.io/documentation/operators/images/scan.png)  RxJava implements this operator as `scan`. 

 #### Sample Code

 
```
Observable.just(1, 2, 3, 4, 5)
    .scan(new Func2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer sum, Integer item) {
            return sum + item;
        }
    }).subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Next: 3
Next: 6
Next: 10
Next: 15
Sequence complete.
```
 * Javadoc: [`scan(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#scan(rx.functions.Func2))
   ![scan](http://reactivex.io/documentation/operators/images/scanSeed.png)  There is also a variant of `scan` to which you can pass a seed value to pass to the accumulator function the first time it is called (for the first emission from the source Observable) in place of the result from the missing prior call to the accumulator. Note that if you use this version, `scan` will emit this seed value as its own initial emission. Note also that passing a seed of `null` is *not* the same as passing no seed at all. A `null` seed is a valid variety of seed. 

 * Javadoc: [`scan(R,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#scan(R,%20rx.functions.Func2))
   This operator does not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJS `expand scan`

     ![scan](http://reactivex.io/documentation/operators/images/scan.png)  RxJS implements the `scan` operator. 

 #### Sample Code

 
```
var source = Rx.Observable.range(1, 3)
    .scan(
        function (acc, x) {
            return acc + x;
        });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 1
Next: 3
Next: 6
Completed
```
    ![scan](http://reactivex.io/documentation/operators/images/scanSeed.js.png)  You can optionally pass `scan` a seed value as an additional parameter. `scan` will pass this seed value to the accumulator function the first time it is called (for the first emission from the source Observable) in place of the result from the missing prior call to the accumulator. 

 #### Sample Code

 
```
var source = Rx.Observable.range(1, 3)
    .scan( function (acc, x) {
            return acc * x;
           }, 1 );

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 1
Next: 2
Next: 6
Completed
```
  `scan` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

  ![expand](http://reactivex.io/documentation/operators/images/expand.png)  RxJS also implements the `expand` operator, which is somewhat similar. Rather than applying the function to the previous return value of the function combined with the next item emitted from the source Observable, such that the number of items it emits is equal to the number emitted by the source Observable, `expand` simply feeds the return value from the function back into the function without regard to future emissions from the Observable, such that it will just continue to create new values at its own pace. 

 #### Sample Code

 
```
var source = Rx.Observable.return(42)
    .expand(function (x) { return Rx.Observable.return(42 + x); })
    .take(5);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Next: 84
Next: 126
Next: 168
Next: 210
Completed
```
 `expand` is found in each of the following distributions:

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.experimental.js`

 `expand` requires one of the following distributions:

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `scan`

       RxPHP implements this operator as `scan`. 

  Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/scan/scan.php

//Without a seed
$source = Rx\Observable::range(1, 3);

$subscription = $source
    ->scan(function ($acc, $x) {
        return $acc + $x;
    })
    ->subscribe($createStdoutObserver());
```
  
```
Next value: 1
Next value: 3
Next value: 6
Complete!
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/scan/scan-with-seed.php

//With a seed
$source = Rx\Observable::range(1, 3);

$subscription = $source
    ->scan(function ($acc, $x) {
        return $acc * $x;
    }, 1)
    ->subscribe($createStdoutObserver());
```
  
```
Next value: 1
Next value: 2
Next value: 6
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/scan.html>

Distinct
========

 
> suppress duplicate items emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#distinct)  The Distinct operator filters an Observable by only allowing items through that have not already been emitted. 


 In some implementations there are variants that allow you to adjust the criteria by which two items are considered “distinct.” In some, there is a variant of the operator that only compares an item against its immediate predecessor for distinctness, thereby filtering only *consecutive* duplicate items from the sequence. 

  #### See Also

 * [Filter](filter)
* [Introduction to Rx: Distinct and DistinctUntilChanged](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#Distinct)
* [RxMarbles: `distinct`](http://rxmarbles.com/#distinct)
* [RxMarbles: `distinctUntilChanged`](http://rxmarbles.com/#distinctUntilChanged)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `distinct distinctUntilChanged`

     ![distinct](http://reactivex.io/documentation/operators/images/distinct.png)  RxGroovy implements this operator as `distinct`. 

 * Javadoc: [`distinct()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinct())
   ![distinct](http://reactivex.io/documentation/operators/images/distinct.key.png)  There is also a variant of this operator that takes a function as a parameter. This function operates on items emitted by the source Observable to generate a “key.” It is these keys, then, and not the items themselves, that `distinct` will compare to determine whether or not two items are distinct. 

 * Javadoc: [`distinct(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinct(rx.functions.Func1))
   ![distinctUntilChanged](http://reactivex.io/documentation/operators/images/distinctUntilChanged.png)  RxGroovy also implements the `distinctUntilChanged` operator. It only compares emitted items from the source Observable against their immediate predecessors in order to determine whether or not they are distinct. 

 * Javadoc: [`distinctUntilChanged()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinctUntilChanged())
   ![distinctUntilChanged](http://reactivex.io/documentation/operators/images/distinctUntilChanged.key.png)  As with `distinct`, there is also a version of `distinctUntilChanged` that accepts a key selector function and that uses the resulting key to determine whether or not two adjacently-emitted items are distinct. 

 * Javadoc: [`distinctUntilChanged(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinctUntilChanged(rx.functions.Func1))
   `distinct` and `distinctUntilChanged` do not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJava 1․x `distinct distinctUntilChanged`

     ![distinct](http://reactivex.io/documentation/operators/images/distinct.png)  RxJava implements this operator as `distinct`. 

 #### Sample Code

 
```
Observable.just(1, 2, 1, 1, 2, 3)
          .distinct()
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Next: 2
Next: 3
Sequence complete.
```
 * Javadoc: [`distinct()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinct())
   ![distinct](http://reactivex.io/documentation/operators/images/distinct.key.png)  There is also a variant of this operator that takes a function as a parameter. This function operates on items emitted by the source Observable to generate a “key.” It is these keys, then, and not the items themselves, that `distinct` will compare to determine whether or not two items are distinct. 

 * Javadoc: [`distinct(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinct(rx.functions.Func1))
   ![distinctUntilChanged](http://reactivex.io/documentation/operators/images/distinctUntilChanged.png)  RxJava also implements the `distinctUntilChanged` operator. It only compares emitted items from the source Observable against their immediate predecessors in order to determine whether or not they are distinct. 

 * Javadoc: [`distinctUntilChanged()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinctUntilChanged())
   ![distinctUntilChanged](http://reactivex.io/documentation/operators/images/distinctUntilChanged.key.png)  As with `distinct`, there is also a version of `distinctUntilChanged` that accepts a key selector function and that uses the resulting key to determine whether or not two adjacently-emitted items are distinct. 

 * Javadoc: [`distinctUntilChanged(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#distinctUntilChanged(rx.functions.Func1))
   `distinct` and `distinctUntilChanged` do not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJS `distinct distinctUntilChanged`

     ![distinct](http://reactivex.io/documentation/operators/images/distinct.png)  In RxJS, the `distinct` operator has two optional parameters: 

 1. a function that accepts an item emitted by the source Observable and returns a *key* which will be used instead of the item itself when comparing two items for distinctness
2. a function that accepts two items (or two keys) and compares them for distinctness, returning `false` if they are distinct (an equality function is the default if you do not supply your own function here)

 #### Sample Code

 
```
/* Without key selector */
var source = Rx.Observable.fromArray([
        42, 24, 42, 24
    ])
    .distinct();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x.toString()); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Next: 24
Completed
```
 
```
/* With key selector */
var source = Rx.Observable.fromArray([
        {value: 42}, {value: 24}, {value: 42}, {value: 24}
    ])
    .distinct(function (x) { return x.value; });

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x.toString());
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: { value: 42 }
Next: { value: 24 }
Completed
```
   ![distinctUntilChanged](http://reactivex.io/documentation/operators/images/distinctUntilChanged.png)  RxJS also has a `distinctUntilChanged` operator. It only compares emitted items from the source Observable against their immediate predecessors in order to determine whether or not they are distinct. It takes the same two optional parameters as the `distinct` operator. 

 #### Sample Code

 
```
/* Without key selector */
var source = Rx.Observable.fromArray([
        24, 42, 24, 24
    ])
    .distinctUntilChanged();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 24
Next: 42
Next: 24
Completed
```
 
```
/* With key selector */
var source = Rx.Observable.fromArray([
        {value: 24}, {value: 42}, {value: 42}, {value: 24}
    ])
    .distinctUntilChanged(function (x) { return x.value; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x.toString()); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: { value: 24 }
Next: { value: 42 }
Next: { value: 24 }
Completed
```
   `distinct` and `distinctUntilChanged` are found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `distinct distinctKey distinctUntilChanged distinctUntilKeyChanged`

       RxPHP implements this operator as `distinct`. 

  Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/distinct/distinct.php

$source = \Rx\Observable::fromArray([
    42, 24, 42, 24
])->distinct();

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Next value: 24
Complete!
```
      RxPHP also has an operator `distinctKey`. 

  Variant of distinct that takes a key selector 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/distinct/distinctKey.php

$source = \Rx\Observable::fromArray([
    ['id' => '42'],
    ['id' => '24'],
    ['id' => '42'],
    ['id' => '24']
])
    ->distinctKey(function ($x) {
        return $x['id'];
    })
    ->map(function ($x) {
        return $x['id'];
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Next value: 24
Complete!
```
      RxPHP also has an operator `distinctUntilChanged`. 

  A variant of distinct that only compares emitted items from the source Observable against their immediate predecessors in order to determine whether or not they are distinct. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/distinct/distinctUntilChanged.php

$source = \Rx\Observable::fromArray([
    24, 42, 24, 24
])->distinctUntilChanged();

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 24
Next value: 42
Next value: 24
Complete!
```
      RxPHP also has an operator `distinctUntilKeyChanged`. 

  Variant of distinctUntilChanged that takes a key selector and the comparer. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/distinct/distinctUntilKeyChanged.php

$source = \Rx\Observable::fromArray([
    ['id' => '24'],
    ['id' => '42'],
    ['id' => '24'],
    ['id' => '24']
])
    ->distinctUntilKeyChanged(function ($x) {
        return $x['id'];
    })
    ->map(function ($x) {
        return $x['id'];
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 24
Next value: 42
Next value: 24
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/distinct.html>

ElementAt
=========

 
> emit only item *n* emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#elementAt)  The `ElementAt` operator pulls an item located at a specified index location in the sequence of items emitted by the source Observable and emits that item as its own sole emission. 

  #### See Also

 * [First](first)
* [Last](last)
* [Introduction to Rx: ElementAt and ElementAtUntilChanged](http://www.introtorx.com/Content/v1.0.10621.0/06_Inspection.html#ElementAt)
* [RxMarbles: `elementAt`](http://rxmarbles.com/#elementAt)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `elementAt elementAtOrDefault`

     ![elementAt](http://reactivex.io/documentation/operators/images/elementAt.png)  RxGroovy implements this operator as `elementAt`. Pass `elementAt` a zero-based index value and it will emit the solitary item from the source Observable’s sequence that matches that index value (for example, if you pass the index value 5, `elementAt` will emit the sixth item emitted by the source Observable). 


 If you pass in a negative index value, or if the source Observable emits fewer than `*index
 value* + 1` items, `elementAt` will throw an `IndexOutOfBoundsException`. 

 * Javadoc: [`elementAt(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#elementAt(int))
   ![elementAtOrDefault](http://reactivex.io/documentation/operators/images/elementAtOrDefault.png)  RxGroovy also implements the `elementAtOrDefault` operator. It differs from `elementAt` in that it will not throw an exception if the source Observable emits fewer than `*index value* + 1` items. Instead, it will emit a “default” item that you specify with an additional parameter to `elementAtOrDefault`. 


 If you pass in a negative index value, `elementAt` will throw an `IndexOutOfBoundsException`. 

 * Javadoc: [`elementAtOrDefault(int,T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#elementAtOrDefault(int,%20T))
   `elementAt` and `elementAtOrDefault` do not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJava 1․x `elementAt elementAtOrDefault`

     ![elementAt](http://reactivex.io/documentation/operators/images/elementAt.png)  RxGroovy implements this operator as `elementAt`. Pass `elementAt` a zero-based index value and it will emit the solitary item from the source Observable’s sequence that matches that index value (for example, if you pass the index value 5, `elementAt` will emit the sixth item emitted by the source Observable). 


 If you pass in a negative index value, or if the source Observable emits fewer than `*index
 value* + 1` items, `elementAt` will throw an `IndexOutOfBoundsException`. 

 * Javadoc: [`elementAt(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#elementAt(int))
   ![elementAtOrDefault](http://reactivex.io/documentation/operators/images/elementAtOrDefault.png)  RxGroovy also implements the `elementAtOrDefault` operator. It differs from `elementAt` in that it will not throw an exception if the source Observable emits fewer than `*index value* + 1` items. Instead, it will emit a “default” item that you specify with an additional parameter to `elementAtOrDefault`. 


 If you pass in a negative index value, `elementAt` will throw an `IndexOutOfBoundsException`. 

 * Javadoc: [`elementAtOrDefault(int,T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#elementAtOrDefault(int,%20T))
   `elementAt` and `elementAtOrDefault` do not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJS `elementAt`

     ![elementAt](http://reactivex.io/documentation/operators/images/elementAt.png)  RxJS implements this operator as `elementAt`. Pass `elementAt` a zero-based index value and it will emit the solitary item from the source Observable’s sequence that matches that index value (for example, if you pass the index value 5, `elementAt` will emit the sixth item emitted by the source Observable). 


 If there is no element in the source sequence with the index value you specify, `elementAt` will issue an `onError` notification: “`Argument out of range`” 

 #### Sample Code

 
```
var source = Rx.Observable.fromArray([1,2,3,4])
    .elementAt(1);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 2
Completed
```
  You may optionally pass in a default value that `elementAt` will emit if the source Observable emits no values: 

 #### Sample Code

 
```
var source = Rx.Observable.fromArray([])
    .element({defaultValue: 23});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 23
Completed
```
   `elementAt` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  They require one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/elementat>

Filter
======

 
> emit only those items from an Observable that pass a predicate test

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#filter)  The Filter operator filters an Observable by only allowing items through that pass a test that you specify in the form of a predicate function. 

  #### See Also

 * [Introduction to Rx: Where](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#Where)
* [Introduction to Rx: Cast and OfType](http://www.introtorx.com/Content/v1.0.10621.0/08_Transformation.html#CastAndOfType)
* [RxMarbles: `filter`](http://rxmarbles.com/#filter)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `filter ofType`

     ![filter](http://reactivex.io/documentation/operators/images/filter.png)  RxGroovy implements this operator as `filter`. You can filter an Observable, discarding any items that do not meet some test, by passing a filtering function into the `filter` operator. For example, the following code filters a list of integers, emitting only those that are even (that is, where the remainder from dividing the number by two is zero): 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);

numbers.filter({ 0 == (it % 2) }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
2
4
6
8
Sequence complete
```
  `filter` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`filter(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#filter(rx.functions.Func1))
   ![ofType](http://reactivex.io/documentation/operators/images/ofClass.png)  There is also a specialized form of the Filter operator in RxGroovy that filters an Observable so that it only emits items of a particular class. 


 `ofType` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`ofType(Class)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#ofType(java.lang.Class))
       ###  RxJava 1․x `filter ofType`

     ![filter](http://reactivex.io/documentation/operators/images/filter.png)  RxJava implements this operator as `filter`. 

 #### Sample Code

 
```
Observable.just(1, 2, 3, 4, 5)
          .filter(new Func1<Integer, Boolean>() {
              @Override
              public Boolean call(Integer item) {
                return( item < 4 );
              }
          }).subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Next: 2
Next: 3
Sequence complete.
```
  `filter` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`filter(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#filter(rx.functions.Func1))
   ![ofType](http://reactivex.io/documentation/operators/images/ofClass.png)  There is also a specialized form of the Filter operator in RxJava that filters an Observable so that it only emits items of a particular class. 


 `ofType` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`ofType(Class)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#ofType(java.lang.Class))
       ###  RxJS `filter where`

     ![filter](http://reactivex.io/documentation/operators/images/filter.png)  RxJS implements this operator under two names, but with identical behavior: `filter` and `where`. This operator takes two parameters: the predicate function, and an optional object that will represent that function’s “`this`” context when it executes. 


 The predicate function itself takes three arguments: 

 1. the item from the source Observable to be, or not be, filtered
2. the zero-based index of this item in the source Observable’s sequence
3. the source Observable object

  Write the predicate function so that it returns `true` for those items you want to pass through the filter to the next observer, and `false` for those items you want the filter to block and suppress. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 5)
  .filter(function (x, idx, obs) {
    return x % 2 === 0;
  });

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 2
Next: 4
Completed
```
   `filter` and `where` are found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `filter where`

       RxPHP implements this operator as `filter`. 

  Emit only those items from an Observable that pass a predicate test. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/filter/filter.php

$observable = Rx\Observable::fromArray([21, 42, 84]);
$observable
    ->filter(function ($elem) {
        return $elem >= 42;
    })
    ->subscribe($stdoutObserver);
```
  
```
Next value: 42
Next value: 84
Complete!
```
      RxPHP also has an operator `where`. 

  Alias for filter 

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/filter.html>

Window
======

 
> periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time

  ![Window](http://reactivex.io/documentation/operators/images/window.C.png)  Window is similar to [Buffer](buffer), but rather than emitting packets of items from the source Observable, it emits Observables, each one of which emits a subset of items from the source Observable and then terminates with an `onCompleted` notification. 


 Like Buffer, Window has many varieties, each with its own way of subdividing the original Observable into the resulting Observable emissions, each one of which contains a “window” onto the original emitted items. In the terminology of the Window operator, when a window “opens,” this means that a new Observable is emitted and that Observable will begin emitting items emitted by the source Observable. When a window “closes,” this means that the emitted Observable stops emitting items from the source Observable and terminates with an `onCompleted` notification to its observers. 

  #### See Also

 * [Buffer](buffer)
* [Introduction to Rx: Window](http://www.introtorx.com/Content/v1.0.10621.0/17_SequencesOfCoincidence.html#Window)
* [101 Rx Samples: Window](http://rxwiki.wikidot.com/101samples#toc38)

 Language-Specific Information
-----------------------------

    ###  RxClojure `partition-all`

     RxClojure implements this operator as `partition-all`: 

  ![partition-all](http://reactivex.io/documentation/operators/images/partition-all.png)  `partition-all` opens its first window immediately. It opens a new window beginning with every `step` item from the source Observable (so, for example, if `step` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `n` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `step = n` (which is the default if you omit the `step` parameter) then the window size is the same as the step size and there will be a one-to-one correspondence between the items emitted by the source Observable and the items emitted by the collection of window Observables. If `step < n` the windows will overlap by `n − step` items; if `step > n` the windows will drop `step − n` items from the source Observable between every window. 

       ###  RxCpp `window window_with_time window_with_time_or_count`

     RxCpp implements this operator as two variants of `window`, two variants of `window_with_time`, and as `window_with_time_or_count`: 

 #### `window(count)`

  ![window(count)](http://reactivex.io/documentation/operators/images/window3.png)  This variant of `window` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### `window(count, skip)`

  ![window(count, skip)](http://reactivex.io/documentation/operators/images/window4.png)  This variant of `window` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `window(source, count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

  #### 
`window_with_time(period`[`, coordination`]`)`

  ![window_with_time(period[,coordination])](http://reactivex.io/documentation/operators/images/window_with_time5.png)  This variant of `window_with_time` opens its first window immediately. It closes the currently open window and opens another one every `period` of time (a Duration, optionally computed by a given Coordination). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window_with_time` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### 
`window_with_time(period, skip`[`, coordination`]`)`

  ![window_with_time(period,skip[,coordination])](http://reactivex.io/documentation/operators/images/window_with_time7.png)  This variant of `window_with_time` opens its first window immediately. It closes the currently open window after `period` amount of time has passed since it was opened, and opens a new window after `skip` amount of time has passed since the previous window was opened (both times are Durations, optionally computed by a given Coordination). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window_with_time` may emit windows that overlap or that have gaps, depending on whether `skip` is less than or greater than `period`. 

  #### 
`window_with_time_or_count(period, count`[`, coordination`]`)`

  ![window_with_time_or_count(period,count[,coordination])](http://reactivex.io/documentation/operators/images/window_with_time_or_count.png)  `window_with_time_or_count` opens its first window immediately. It closes the currently open window and opens another one every `period` of time (optionally computed by a given Coordination) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. `window_with_time_or_count` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

       ###  RxGroovy `window`

     There are several varieties of Window in RxGroovy. 

 #### `window(closingSelector)`

  ![window(closingSelector)](http://reactivex.io/documentation/operators/images/window1.png)  This variant of `window` opens its first window immediately. It closes the currently open window and immediately opens a new one each time it observes an object emitted by the Observable that is returned from `closingSelector`. In this way, this variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

 * Javadoc: [`window(Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(rx.functions.Func0))
  #### `window(windowOpenings, closingSelector)`

  ![window(windowOpenings, closingSelector)](http://reactivex.io/documentation/operators/images/window2.png)  This variant of `window` opens a window whenever it observes the `windowOpenings` Observable emit an `Opening` object and at the same time calls `closingSelector` to generate a closing Observable associated with that window. When that closing Observable emits an object, `window` closes that window. Since the closing of currently open windows and the opening of new windows are activities that are regulated by independent Observables, this variant of `window` may create windows that overlap (duplicating items from the source Observable) or that leave gaps (discarding items from the source Observable). 

 * Javadoc: [`window(Observable,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(rx.Observable,%20rx.functions.Func1))
  #### `window(count)`

  ![window(count)](http://reactivex.io/documentation/operators/images/window3.png)  This variant of `window` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

 * Javadoc: [`window(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(int))
  #### `window(count, skip)`

  ![window(count, skip)](http://reactivex.io/documentation/operators/images/window4.png)  This variant of `window` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `window(source, count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

 * Javadoc: [`window(int,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(int,%20int))
  #### 
`window(timespan, unit`[`, scheduler`]`)`

  ![window(timespan, unit[, scheduler])](http://reactivex.io/documentation/operators/images/window5.png)  This variant of `window` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

 * Javadoc: [`window(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`window(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
  #### 
`window(timespan, unit, count`[`, scheduler`]`)`

  ![window(timespan, unit, count[, scheduler])](http://reactivex.io/documentation/operators/images/window6.png)  This variant of `window` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

 * Javadoc: [`window(long,TimeUnit,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit,%20int))
* Javadoc: [`window(long,TimeUnit,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit,%20int,%20rx.Scheduler))
  #### 
`window(timespan, timeshift, unit`[`, scheduler`]`)`

  ![window(timespan, timeshift, unit[, scheduler])](http://reactivex.io/documentation/operators/images/window7.png)  This variant of `window` opens its first window immediately, and thereafter opens a new window every `timeshift` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)). It closes a currently open window after `timespan` period of time has passed since that window was opened. It will also close any currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. Depending on how you set `timespan` and `timeshift` the windows that result from this operation may overlap or may have gaps. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

 * Javadoc: [`window(long,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`window(long,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   You can use the Window operator to implement backpressure (that is, to cope with an Observable that may produce items too quickly for its observer to consume). 

  ![Window as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.window1.png)  Window can reduce a sequence of many items to a sequence of fewer windows-of-items, making them more manageable. You could, for example, emit a window of items from a bursty Observable periodically, at a regular interval of time. 

 #### Sample Code

 
```
Observable<Observable<Integer>> burstyWindowed = bursty.window(500, TimeUnit.MILLISECONDS);
```
   ![Window as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.window2.png)  Or you could choose to emit a new window of items for every *n* items emitted by the bursty Observable. 

 #### Sample Code

 
```
Observable<Observable<Integer>> burstyWindowed = bursty.window(5);
```
        ###  RxJava 1․x `window`

     There are several varieties of Window in RxJava. 

 #### `window(closingSelector)`

  ![window(closingSelector)](http://reactivex.io/documentation/operators/images/window1.png)  This variant of `window` opens its first window immediately. It closes the currently open window and immediately opens a new one each time it observes an object emitted by the Observable that is returned from `closingSelector`. In this way, this variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

 * Javadoc: [`window(Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(rx.functions.Func0))
  #### `window(windowOpenings, closingSelector)`

  ![window(windowOpenings, closingSelector)](http://reactivex.io/documentation/operators/images/window2.png)  This variant of `window` opens a window whenever it observes the `windowOpenings` Observable emit an `Opening` object and at the same time calls `closingSelector` to generate a closing Observable associated with that window. When that closing Observable emits an object, `window` closes that window. Since the closing of currently open windows and the opening of new windows are activities that are regulated by independent Observables, this variant of `window` may create windows that overlap (duplicating items from the source Observable) or that leave gaps (discarding items from the source Observable). 

 * Javadoc: [`window(Observable,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(rx.Observable,%20rx.functions.Func1))
  #### `window(count)`

  ![window(count)](http://reactivex.io/documentation/operators/images/window3.png)  This variant of `window` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

 * Javadoc: [`window(int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(int))
  #### `window(count, skip)`

  ![window(count, skip)](http://reactivex.io/documentation/operators/images/window4.png)  This variant of `window` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `window(source, count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

 * Javadoc: [`window(int,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(int,%20int))
  #### 
`window(timespan, unit`[`, scheduler`]`)`

  ![window(timespan, unit[, scheduler])](http://reactivex.io/documentation/operators/images/window5.png)  This variant of `window` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

 * Javadoc: [`window(long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`window(long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
  #### 
`window(timespan, unit, count`[`, scheduler`]`)`

  ![window(timespan, unit, count[, scheduler])](http://reactivex.io/documentation/operators/images/window6.png)  This variant of `window` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

 * Javadoc: [`window(long,TimeUnit,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit,%20int))
* Javadoc: [`window(long,TimeUnit,int,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20java.util.concurrent.TimeUnit,%20int,%20rx.Scheduler))
  #### 
`window(timespan, timeshift, unit`[`, scheduler`]`)`

  ![window(timespan, timeshift, unit[, scheduler])](http://reactivex.io/documentation/operators/images/window7.png)  This variant of `window` opens its first window immediately, and thereafter opens a new window every `timeshift` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)). It closes a currently open window after `timespan` period of time has passed since that window was opened. It will also close any currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. Depending on how you set `timespan` and `timeshift` the windows that result from this operation may overlap or may have gaps. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

 * Javadoc: [`window(long,long,TimeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20long,%20java.util.concurrent.TimeUnit))
* Javadoc: [`window(long,long,TimeUnit,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#window(long,%20long,%20java.util.concurrent.TimeUnit,%20rx.Scheduler))
   You can use the Window operator to implement backpressure (that is, to cope with an Observable that may produce items too quickly for its observer to consume). 

  ![Window as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.window1.png)  Window can reduce a sequence of many items to a sequence of fewer windows-of-items, making them more manageable. You could, for example, emit a window of items from a bursty Observable periodically, at a regular interval of time. 

 #### Sample Code

 
```
Observable<Observable<Integer>> burstyWindowed = bursty.window(500, TimeUnit.MILLISECONDS);
```
   ![Window as a backpressure strategy](http://reactivex.io/documentation/operators/images/bp.window2.png)  Or you could choose to emit a new window of items for every *n* items emitted by the bursty Observable. 

 #### Sample Code

 
```
Observable<Observable<Integer>> burstyWindowed = bursty.window(5);
```
        ###  RxJS `window windowWithCount windowWithTime windowWithTimeOrCount`

    #### `window(windowClosingSelector)`

  ![window(windowClosingSelector)](http://reactivex.io/documentation/operators/images/window1.cs.png)  #### `window(windowOpenings, windowClosingSelector)`

  ![window(windowOpenings,windowClosingSelector)](http://reactivex.io/documentation/operators/images/window2.ocs.png)  #### `window(windowBoundaries)`

  ![window(windowBoundaries)](http://reactivex.io/documentation/operators/images/window8.b.png)   This variant of `window` takes a second Observable as a parameter. Whenever this second Observable emits an item, `window` closes the current Observable window (if any) and opens a new one. 

   #### `windowWithCount(count)`

  ![windowWithCount(count)](http://reactivex.io/documentation/operators/images/windowWithCount3.png)   This variant of `windowWithCount` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `windowWithCount` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

   #### `windowWithCount(count, skip)`

  ![windowWithCount(count,skip)](http://reactivex.io/documentation/operators/images/windowWithCount4.png)   This variant of `windowWithCount` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `windowWithCount(count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

   #### 
`windowWithTime(timeSpan`[`,scheduler`]`)`

  ![windowWithTime(timeSpan)](http://reactivex.io/documentation/operators/images/windowWithTime5.png)  This variant of `windowWithTime` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (in milliseconds, optionally measured on a particular [Scheduler](../scheduler)). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `windowWithTime` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `windowWithTime` uses the `timeout` Scheduler for its timer by default. 

  #### 
`windowWithTime(timeSpan,timeShift`[`,scheduler`]`)`

  ![windowWithTime(timeSpan,timeShift)](http://reactivex.io/documentation/operators/images/windowWithTime7.png)  This variant of `windowWithTime` opens its first window immediately, and thereafter opens a new window every `timeshift` milliseconds (optionally measured on a particular [Scheduler](../scheduler)). It closes a currently open window after `timespan` milliseconds have passed since that window was opened. It will also close any currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. Depending on how you set `timespan` and `timeshift` the windows that result from this operation may overlap or may have gaps. 


 If you do not specify a Scheduler, this variant of `windowWithTime` uses the `timeout` Scheduler for its timer by default. 

  #### 
`windowWithTimeOrCount(timeSpan,count`[`,scheduler`]`)`

  ![windowWithTimeOrCount(timeSpan,count)](http://reactivex.io/documentation/operators/images/windowWithTimeOrCount6.png)  `windowWithTimeOrCount` opens its first window immediately. It closes the currently open window and opens another one every `timespan` milliseconds (optionally measured on a particular [Scheduler](../scheduler)) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. `windowWithTimeOrCount` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `windowWithTimeOrCount` uses the `timeout` Scheduler for its timer by default. 

       ###  RxKotlin `window`

     There are several varieties of Window in RxKotlin. 

 #### `window(closingSelector)`

  ![window(closingSelector)](http://reactivex.io/documentation/operators/images/window1.png)  This variant of `window` opens its first window immediately. It closes the currently open window and immediately opens a new one each time it observes an object emitted by the Observable that is returned from `closingSelector`. In this way, this variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### `window(windowOpenings, closingSelector)`

  ![window(windowOpenings, closingSelector)](http://reactivex.io/documentation/operators/images/window2.png)  This variant of `window` opens a window whenever it observes the `windowOpenings` Observable emit an `Opening` object and at the same time calls `closingSelector` to generate a closing Observable associated with that window. When that closing Observable emits an object, `window` closes that window. Since the closing of currently open windows and the opening of new windows are activities that are regulated by independent Observables, this variant of `window` may create windows that overlap (duplicating items from the source Observable) or that leave gaps (discarding items from the source Observable). 

  #### `window(count)`

  ![window(count)](http://reactivex.io/documentation/operators/images/window3.png)  This variant of `window` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### `window(count, skip)`

  ![window(count, skip)](http://reactivex.io/documentation/operators/images/window4.png)  This variant of `window` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `window(source, count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

  #### 
`window(timespan, unit`[`, scheduler`]`)`

  ![window(timespan, unit[, scheduler])](http://reactivex.io/documentation/operators/images/window5.png)  This variant of `window` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

  #### 
`window(timespan, unit, count`[`, scheduler`]`)`

  ![window(timespan, unit, count[, scheduler])](http://reactivex.io/documentation/operators/images/window6.png)  This variant of `window` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

  #### 
`window(timespan, timeshift, unit`[`, scheduler`]`)`

  ![window(timespan, timeshift, unit[, scheduler])](http://reactivex.io/documentation/operators/images/window7.png)  This variant of `window` opens its first window immediately, and thereafter opens a new window every `timeshift` period of time (measured in `unit`, and optionally on a particular [`Scheduler`](../scheduler)). It closes a currently open window after `timespan` period of time has passed since that window was opened. It will also close any currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. Depending on how you set `timespan` and `timeshift` the windows that result from this operation may overlap or may have gaps. 


 If you do not specify a Scheduler, this variant of `window` uses the `computation` Scheduler for its timer by default. 

       ###  RxNET `Window`

     There are several variants of the Window operator in Rx.NET. 

 #### `Window(windowClosingSelector)`

  ![window(windowClosingSelector)](http://reactivex.io/documentation/operators/images/window1.net.png)  This variant of `Window` opens its first window immediately and calls the `windowClosingSelector` function to obtain a second Observable. Whenever this second Observable emits a `TWindowClosing` object, `Window` closes the currently open window, and immediately opens a new one. It repeats this process until either Observable terminates. In this way, this variant of `Window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable, until the closing selector observable terminates. 

  #### `Window(count)`

  ![window(count)](http://reactivex.io/documentation/operators/images/window3.net.png)  This variant of `Window` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `Window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### 
`Window(timeSpan`[`,scheduler`]`)`

  ![window(timeSpan)](http://reactivex.io/documentation/operators/images/window5.net.png)  This variant of `Window` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (in the form of a `TimeSpan` object, and optionally on a particular [`IScheduler`](../scheduler)). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `Window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### `Window(count,skip)`

  ![window(count,skip)](http://reactivex.io/documentation/operators/images/window4.net.png)  This variant of `Window` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `Window(source, count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

  #### `Window(windowOpenings,windowClosingSelector)`

  ![window(windowOpenings,windowClosingSelector)](http://reactivex.io/documentation/operators/images/window2.net.png)  This variant of `Window` opens a window whenever it observes the `windowOpenings` Observable emit an `TWindowOpening` object and at the same time calls the `windowClosingSelector`, passing it that `TWindowOpening` object, to generate a closing Observable associated with that window. When that closing Observable emits a `TWindowClosing` object, `Window` closes the associated window. Since the closing of currently open windows and the opening of new windows are activities that are regulated by independent Observables, this variant of `Window` may create windows that overlap (duplicating items from the source Observable) or that leave gaps (discarding items from the source Observable). 

  #### 
`Window(timeSpan,count`[`,scheduler`]`)`

  ![window(timeSpan,count)](http://reactivex.io/documentation/operators/images/window6.net.png)  This variant of `Window` opens its first window immediately. It closes the currently open window and opens another one every `timeSpan` period of time (in the form of a `TimeSpan` object, and optionally on a particular [`IScheduler`](../scheduler)) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### 
`Window(timeSpan,timeShift`[`,scheduler`]`)`

  ![window(timeSpan,timeShift)](http://reactivex.io/documentation/operators/images/window7.net.png)  This variant of `Window` opens its first window immediately, and thereafter opens a new window every `timeShift` period of time (in the form of a `TimeSpan` object, and optionally on a particular [`IScheduler`](../scheduler)). It closes a currently open window after `timeSpan` period of time has passed since that window was opened. It will also close any currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. Depending on how you set `timeSpan` and `timeShift` the windows that result from this operation may overlap or may have gaps. 

       ###  RxPY `window window_with_count window_with_time window_with_time_or_count`

     RxPY implements this operator with several variants of four different functions. 

 #### `window(window_closing_selector)`

  ![window(window_closing_selector)](http://reactivex.io/documentation/operators/images/window1.net.png)  This variant of `window` opens its first window immediately and calls the `closing_selector` function to obtain a second Observable. When this second Observable emits an item, `window` closes the currently open window, immediately opens a new one, and again calls the `closing_selector` function to obtain a fresh Observable. It repeats this process until the source Observable terminates. In this way, this variant of `window` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### `window(window_openings,window_closing_selector)`

  ![window(window_openings,window_closing_selector)](http://reactivex.io/documentation/operators/images/window2.png)  This variant of `window` opens a window whenever it observes the `window_openings` Observable emit an item, and at the same time calls `closing_selector` to generate a closing Observable associated with that window. When that closing Observable emits an object, `window` closes that window. Since the closing of currently open windows and the opening of new windows are activities that are regulated by independent Observables, this variant of `window` may create windows that overlap (duplicating items from the source Observable) or that leave gaps (discarding items from the source Observable). 

  #### `window(window_openings)`

  ![window(window_openings)](http://reactivex.io/documentation/operators/images/window8.png)  This variant of `window` takes a second Observable as a parameter. Whenever this second Observable emits an item, `window` closes the current Observable window (if any) and opens a new one. 

  #### `window_with_count(count)`

  ![window_with_count(count)](http://reactivex.io/documentation/operators/images/window_with_count3.png)  This variant of `window_with_count` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window_with_count` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 

  #### `window_with_count(count,skip)`

  ![window_with_count(count,skip)](http://reactivex.io/documentation/operators/images/window_with_count4.png)  This variant of `window_with_count` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `window_with_count(count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

  #### 
`window_with_time(timespan`[`,scheduler`]`)`

  ![window_with_time(timespan)](http://reactivex.io/documentation/operators/images/window_with_time5.py.png)  #### 
`window_with_time(timespan,timeshift`[`,scheduler`]`)`

  ![window_with_time(timespan,timeshift)](http://reactivex.io/documentation/operators/images/window_with_time7.py.png)  This variant of `window_with_time` opens its first window immediately. It closes the currently open window and opens another one every `timespan` milliseconds (optionally measured on a particular [`Scheduler`](../scheduler)). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. This variant of `window_with_time` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window_with_time` uses the `timeout` Scheduler for its timer by default. 

  #### 
`window_with_time_or_count(timespan,count`[`,scheduler`]`)`

  ![window_with_time_or_count(timespan,count)](http://reactivex.io/documentation/operators/images/window_with_time_or_count.py.png)  `window_with_time_or_count` opens its first window immediately. It closes the currently open window and opens another one every `timespan` milliseconds (optionally measured on a particular [Scheduler](../scheduler)) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. `window_with_time_or_count` emits a series of non-overlapping windows whose collective emissions correspond one-to-one with those of the source Observable. 


 If you do not specify a Scheduler, this variant of `window_with_time_or_count` uses the `timeout` Scheduler for its timer by default. 

       ###  Rxrb `window_with_count`

    #### `window_with_count(count,skip)`

  ![window_with_count(count,skip)](http://reactivex.io/documentation/operators/images/window_with_count4.png)  Rx.rb implements this operator as `window_with_count`. It opens its first window immediately. It then opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then there is a one-to-one correspondence between the items emitted by the source Observable and those emitted by the window Observables; if `skip < count` the windows will overlap by `count − skip` items; if `skip > count` the windows will drop `skip − count` items from the source Observable between every window. 

       ###  RxScala `sliding tumbling`

     RxScala implements this operator as `sliding` (creates windows that may overlap or have gaps) and `tumbling` (creates windows whose collective emissions match those of the source Observable one-to-one). 

 #### 
`sliding(timespan,timeshift,count`[`,scheduler`]`)`

  ![sliding(timespan,timeshift,count)](http://reactivex.io/documentation/operators/images/sliding9.png)  This variant of `sliding` opens its first window immediately, and thereafter opens a new window every `timeshift` period of time (in the form of a `Duration` object, and optionally on a particular [`Scheduler`](../scheduler)). It closes a currently open window after `timespan` period of time has passed since that window was opened or once `count` items have been emitted on that window. It will also close any currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. 

  #### 
`sliding(timespan,timeshift`[`,scheduler`]`)`

  ![sliding(timespan,timeshift)](http://reactivex.io/documentation/operators/images/sliding7.png)  This variant of `sliding` opens its first window immediately, and thereafter opens a new window every `timeshift` period of time (in the form of a `Duration` object, and optionally on a particular [`Scheduler`](../scheduler)). It closes a currently open window after `timespan` period of time has passed since that window was opened. It will also close any currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. 

  #### `sliding(count,skip)`

  ![sliding(count,skip)](http://reactivex.io/documentation/operators/images/sliding4.png)  This variant of `sliding` opens its first window immediately. It opens a new window beginning with every `skip` item from the source Observable (so, for example, if `skip` is 3, then it opens a new window starting with every third item). It closes each window when that window has emitted `count` items or if it receives an `onCompleted` or `onError` notification from the source Observable. If `skip = count` then this behaves the same as `tumbling(count)`; if `skip < count` this will emit windows that overlap by `count − skip` items; if `skip > count` this will emit windows that drop `skip − count` items from the source Observable between every window. 

  #### `sliding(openings,closings)`

  ![sliding(openings,closings)](http://reactivex.io/documentation/operators/images/sliding2.png)  This variant of `sliding` opens a window whenever it observes the `openings` Observable emit an `Opening` object and at the same time calls `closings` to generate a closing Observable associated with that window. When that closing Observable emits an item, `sliding` closes that window. 

  #### 
`tumbling(timespan,count`[`,scheduler`]`)`

  ![tumbling(timespan,count)](http://reactivex.io/documentation/operators/images/tumbling6.png)  This variant of `tumbling` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (a `Duration`, optionally measured on a particular [`Scheduler`](../scheduler)) or whenever the currently open window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. 

  #### 
`tumbling(timespan`[`,scheduler`]`)`

  ![tumbling(timespan)](http://reactivex.io/documentation/operators/images/tumbling5.png)  This variant of `tumbling` opens its first window immediately. It closes the currently open window and opens another one every `timespan` period of time (a `Duration`, optionally measured on a particular [`scheduler`](../scheduler)). It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. 

  #### `tumbling(count)`

  ![tumbling(count)](http://reactivex.io/documentation/operators/images/tumbling3.png)  This variant of `tumbling` opens its first window immediately. It closes the currently open window and immediately opens a new one whenever the current window has emitted `count` items. It will also close the currently open window if it receives an `onCompleted` or `onError` notification from the source Observable. 

  #### `tumbling(boundary)`

  ![tumbling(boundary)](http://reactivex.io/documentation/operators/images/tumbling8.png)  This variant of `tumbling` takes a second Observable as a parameter. Whenever this second Observable emits an item, `tumbling` closes the current Observable window (if any) and opens a new one. 

     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/window.html>

From
====

 
> convert various other objects and data types into Observables

  ![From](http://reactivex.io/documentation/operators/images/from.c.png)  When you work with Observables, it can be more convenient if all of the data you mean to work with can be represented as Observables, rather than as a mixture of Observables and other types. This allows you to use a single set of operators to govern the entire lifespan of the data stream. 


 Iterables, for example, can be thought of as a sort of synchronous Observable; Futures, as a sort of Observable that always emits only a single item. By explicitly converting such objects to Observables, you allow them to interact as peers with other Observables. 


 For this reason, most ReactiveX implementations have methods that allow you to convert certain language-specific objects and data structures into Observables. 

  See Also
--------

 * [Just](just)
* [Start](start)
* [101 Rx Samples: Observation Operators](http://rxwiki.wikidot.com/101samples#toc5)
* [RxJava Tutorial 03: Observable from, just, & create methods](https://www.youtube.com/watch?v=sDqrlNprY24)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `decode from fromAction fromCallable fromFunc0 fromRunnable runAsync`

     ![from](http://reactivex.io/documentation/operators/images/from.Future.png)  In RxGroovy, the `from` operator can convert a Future, an Iterable, or an Array. In the case of an Iterable or an Array, the resulting Observable will emit each item contained in the Iterable or Array. 


 In the case of a Future, it will emit the single result of the `get` call. You may optionally pass the version of `from` that accepts a future two additional parameters indicating a timeout span and the units of time that span is denominated in. The resulting Observable will terminate with an error if that span of time passes before the Future responds with a value. 


 `from` does not by default operate on any particular [Scheduler](../scheduler), however you can pass the variant that converts a Future a Scheduler as an optional second parameter, and it will use that Scheduler to govern the Future. 

 * Javadoc: [`from(array)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(T%5B%5D))
* Javadoc: [`from(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.lang.Iterable))
* Javadoc: [`from(Future)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.util.concurrent.Future))
* Javadoc: [`from(Future,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.util.concurrent.Future,%20rx.Scheduler))
* Javadoc: [`from(Future,timout,timeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.util.concurrent.Future,%20long,%20java.util.concurrent.TimeUnit))
   ![fromFunc0](http://reactivex.io/documentation/operators/images/fromFunc0.png)  In addition, in the `RxJavaAsyncUtil` package, you have available to you the following operators that convert actions, callables, functions, and runnables into Observables that emit the results of those things: 

 * `fromAction`
* `fromCallable`
* `fromFunc0`
* `fromRunnable`

  See the [Start](start) operator for more information about those operators. 

    ![from](http://reactivex.io/documentation/operators/images/St.from.png)  Note that there is also a `from` operator that is a method of the optional `StringObservable` class. It converts a stream of characters or a `Reader` into an Observable that emits byte arrays or Strings. 

   In the separate `RxJavaAsyncUtil` package, which is not included by default with RxGroovy, there is also a `runAsync` function. Pass `runAsync` an `Action` and a [`Scheduler`](../scheduler), and it will return a `StoppableObservable` that uses the specified `Action` to generate items that it emits. 


 The `Action` accepts an `Observer` and a `Subscription`. It uses the `Subscription` to check for the `isUnsubscribed` condition, upon which it will stop emitting items. You can also manually stop a `StoppableObservable` at any time by calling its `unsubscribe` method (which will also unsubscribe the `Subscription` you have associated with the `StoppableObservable`). 


 Because `runAsync` immediately invokes the `Action` and begins emitting the items, it is possible that some items may be lost in the interval between when you establish the `StoppableObservable` with this method and when your `Observer` is ready to receive items. If this is a problem, you can use the variant of `runAsync` that also accepts a [`Subject`](../subject) and pass a `ReplaySubject` with which you can retrieve the otherwise-missing items. 

  ![decode](http://reactivex.io/documentation/operators/images/St.decode.png)  The `StringObservable` class, which is not a default part of RxGroovy, also includes the `decode` operator which converts a stream of multibyte characters into an Observable that emits byte arrays that respect the character boundaries. 

       ###  RxJava 1․x `decode from fromAction fromCallable fromFunc0 fromRunnable runAsync`

     ![from](http://reactivex.io/documentation/operators/images/from.Future.png)  In RxJava, the `from` operator can convert a Future, an Iterable, or an Array. In the case of an Iterable or an Array, the resulting Observable will emit each item contained in the Iterable or Array. 

 #### Sample Code

 
```
Integer[] items = { 0, 1, 2, 3, 4, 5 };
Observable myObservable = Observable.from(items);

myObservable.subscribe(
    new Action1<Integer>() {
        @Override
        public void call(Integer item) {
            System.out.println(item);
        }
    },
    new Action1<Throwable>() {
        @Override
        public void call(Throwable error) {
            System.out.println("Error encountered: " + error.getMessage());
        }
    },
    new Action0() {
        @Override
        public void call() {
            System.out.println("Sequence complete");
        }
    }
);
```
 
```
0
1
2
3
4
5
Sequence complete
```
  In the case of a Future, it will emit the single result of the `get` call. You may optionally pass the version of `from` that accepts a future two additional parameters indicating a timeout span and the units of time that span is denominated in. The resulting Observable will terminate with an error if that span of time passes before the Future responds with a value. 


 `from` does not by default operate on any particular [Scheduler](../scheduler), however you can pass the variant that converts a Future a Scheduler as an optional second parameter, and it will use that Scheduler to govern the Future. 

 * Javadoc: [`from(array)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(T%5B%5D))
* Javadoc: [`from(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.lang.Iterable))
* Javadoc: [`from(Future)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.util.concurrent.Future))
* Javadoc: [`from(Future,Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.util.concurrent.Future,%20rx.Scheduler))
* Javadoc: [`from(Future,timout,timeUnit)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#from(java.util.concurrent.Future,%20long,%20java.util.concurrent.TimeUnit))
   ![fromFunc0](http://reactivex.io/documentation/operators/images/fromFunc0.png)  In addition, in the `RxJavaAsyncUtil` package, you have available to you the following operators that convert actions, callables, functions, and runnables into Observables that emit the results of those things: 

 * `fromAction`
* `fromCallable`
* `fromFunc0`
* `fromRunnable`

  See the [Start](start) operator for more information about those operators. 

    ![from](http://reactivex.io/documentation/operators/images/St.from.png)  Note that there is also a `from` operator that is a method of the optional `StringObservable` class. It converts a stream of characters or a `Reader` into an Observable that emits byte arrays or Strings. 

   In the separate `RxJavaAsyncUtil` package, which is not included by default with RxJava, there is also a `runAsync` function. Pass `runAsync` an `Action` and a [`Scheduler`](../scheduler), and it will return a `StoppableObservable` that uses the specified `Action` to generate items that it emits. 


 The `Action` accepts an `Observer` and a `Subscription`. It uses the `Subscription` to check for the `isUnsubscribed` condition, upon which it will stop emitting items. You can also manually stop a `StoppableObservable` at any time by calling its `unsubscribe` method (which will also unsubscribe the `Subscription` you have associated with the `StoppableObservable`). 


 Because `runAsync` immediately invokes the `Action` and begins emitting the items, it is possible that some items may be lost in the interval between when you establish the `StoppableObservable` with this method and when your `Observer` is ready to receive items. If this is a problem, you can use the variant of `runAsync` that also accepts a [`Subject`](../subject) and pass a `ReplaySubject` with which you can retrieve the otherwise-missing items. 

  ![decode](http://reactivex.io/documentation/operators/images/St.decode.png)  The `StringObservable` class, which is not a default part of RxGroovy, also includes the `decode` operator which converts a stream of multibyte characters into an Observable that emits byte arrays that respect the character boundaries. 

       ###  RxJS `from fromCallback fromEvent fromEventPattern fromNodeCallback fromPromise of ofArrayChanges ofObjectChanges ofWithScheduler pairs`

     There are several, specialized From variants in RxJS: 

  ![from](http://reactivex.io/documentation/operators/images/from.png)  In RxJS, the `from` operator converts an array-like or iterable object into an Observable that emits the items in that array or iterable. A String, in this context, is treated as an array of characters. 


 This operator also takes three additional, optional parameters: 

 2. a transforming function that takes an item from the array or iterable as input and produces an item to be emitted by the resulting Observable as output
3. a second argument to pass into the transforming function as additional context information
4. a [Scheduler](../scheduler) on which this operator should operate

 #### Sample Code

 
```
// Array-like object (arguments) to Observable
function f() {
  return Rx.Observable.from(arguments);
}

f(1, 2, 3).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
```
 
```
Next: 1
Next: 2
Next: 3
Completed
```
 
```
// Any iterable object...
// Set
var s = new Set(['foo', window]);
Rx.Observable.from(s).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
```
 
```
Next: foo
Next: window
Completed
```
 
```
// Map
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Rx.Observable.from(m).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
```
 
```
Next: [1, 2]
Next: [2, 4]
Next: [4, 8]
Completed
```
 
```
// String
Rx.Observable.from("foo").subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
```
 
```
Next: f
Next: o
Next: o
Completed
```
 
```
// Using an arrow function as the map function to manipulate the elements
Rx.Observable.from([1, 2, 3], function (x) { return x + x; }).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
```
 
```
Next: 2
Next: 4
Next: 6
Completed
```
 
```
// Generate a sequence of numbers
Rx.Observable.from({length: 5}, function(v, k) { return k; }).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed
```
  `from` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![fromCallback](http://reactivex.io/documentation/operators/images/fromCallback.png)  The `fromCallback` operator takes a function as a parameter, calls this function, and emits the value returned from it as its single emission. 


 This operator also takes two additional, optional parameters: 

 2. a parameter to pass to the callback function
3. a tranforming function that takes the return value of the callback function as input and returns an item to be emitted by the resulting Observable

 #### Sample Code

 
```
var fs = require('fs'),
    Rx = require('rx');

// Wrap fs.exists
var exists = Rx.Observable.fromCallback(fs.exists);

// Check if file.txt exists
var source = exists('file.txt');

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: true
Completed
```
  `fromCallback` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.async.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.async.compat.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

  There is also a `fromNodeCallback` operator, which is specialized for the types of callback functions found in Node.js. 


 This operator takes three additional, optional parameters: 

 2. a [Scheduler](../scheduler) on which you want to run the Node.js callback
3. a parameter to give to the callback function
4. a tranforming function that takes the return value of the callback function as input and returns an item to be emitted by the resulting Observable

 #### Sample Code

 
```
var fs = require('fs'),
    Rx = require('rx');

// Wrap fs.exists
var rename = Rx.Observable.fromNodeCallback(fs.rename);

// Rename file which returns no parameters except an error
var source = rename('file1.txt', 'file2.txt');

var subscription = source.subscribe(
    function () { console.log('Next: success!'); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: success!
Completed
```
  `fromNodeCallback` is found in the following distributions: 

 * `rx.async.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.async.compat.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

    ![fromEvent](http://reactivex.io/documentation/operators/images/fromEvent.png)  The `fromEvent` operator takes an “element” and an event name as parameters, and it then listens for events of that name taking place on that element. It returns an Observable that emits those events. An “element” may be a simple DOM element, or a NodeList, jQuery element, Zepto Element, Angular element, Ember.js element, or EventEmitter. 


 This operator also takes an optional third parameter: a function that accepts the arguments from the event handler as parameters and returns an item to be emitted by the resulting Observable in place of the event. 

 #### Sample Code

 
```
// using a jQuery element
var input = $('#input');

var source = Rx.Observable.fromEvent(input, 'click');

var subscription = source.subscribe(
    function (x) { console.log('Next: Clicked!'); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

input.trigger('click');
```
 
```
Next: Clicked!
```
 
```
// using a Node.js EventEmitter and the optional third parameter
var EventEmitter = require('events').EventEmitter,
    Rx = require('rx');

var eventEmitter = new EventEmitter();

var source = Rx.Observable.fromEvent(
    eventEmitter,
    'data',
    function (first, second) {
        return { foo: first, bar: second };
    });

var subscription = source.subscribe(
    function (x) {
        console.log('Next: foo -' + x.foo + ', bar -' + x.bar);
    },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

eventEmitter.emit('data', 'baz', 'quux');
```
 
```
Next: foo - baz, bar - quux
```
  `fromEvent` is found in the following distributions: 

 * `rx.async.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.async.compat.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

  The `fromEventPattern` operator is similar, except that instead of taking an element and an event name as parameters, it takes two functions as parameters. The first function attaches an event listener to a variety of events on a variety of elements; the second function removes this set of listeners. In this way you can establish a single Observable that emits items representing a variety of events and a variety of target elements. 

 #### Sample Code

 
```
var input = $('#input');

var source = Rx.Observable.fromEventPattern(
    function add (h) {
        input.bind('click', h);
    },
    function remove (h) {
        input.unbind('click', h);
    }
);

var subscription = source.subscribe(
    function (x) { console.log('Next: Clicked!'); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

input.trigger('click');
```
 
```
Next: Clicked!
```
   ![of](http://reactivex.io/documentation/operators/images/of.png)  The `of` operator accepts a number of items as parameters, and returns an Observable that emits each of these parameters, in order, as its emitted sequence. 

 #### Sample Code

 
```
var source = Rx.Observable.of(1,2,3);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 1
Next: 2
Next: 3
Completed
```
  `of` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

  A variant of this operator, called `ofWithScheduler` takes a [Scheduler](../scheduler) as its first parameter, and operates the resulting Observable on this Scheduler. 

    There is also a `fromPromise` operator that converts a Promise into an Observable, converting its `resolve` calls into `onNext` notifications, and its `reject` calls into `onError` notifications. 


 `fromPromise` is found in the following distributions: 

 * `rx.async.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.async.compat.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

 #### Sample Code

 
```
var promise = new RSVP.Promise(function (resolve, reject) {
   resolve(42);
});

var source = Rx.Observable.fromPromise(promise);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });
```
 
```
Next: 42:
Completed
```
 
```
var promise = new RSVP.Promise(function (resolve, reject) {
   reject(new Error('reason'));
});

var source = Rx.Observable.fromPromise(promise);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });
```
 
```
Error: Error: reject
```
  There is also an `ofArrayChanges` operator that monitors an Array with the `Array.observe` method, and returns an Observable that emits any changes that take place in the array. This operator is found only in the `rx.all.js` distribution. 

 #### Sample Code

 
```
var arr = [1,2,3];
var source = Rx.Observable.ofArrayChanges(arr);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });

arr.push(4)
```
 
```
Next: {type: "splice", object: Array[4], index: 3, removed: Array[0], addedCount: 1}
```
  A similar operator is `ofObjectChanges`. It returns an Observable that emits any changes made to a particular object, as reported by its `Object.observe` method. It is also found only in the `rx.all.js` distribution. 

 #### Sample Code

 
```
var obj = {x: 1};
var source = Rx.Observable.ofObjectChanges(obj);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });

obj.x = 42;
```
 
```
Next: {type: "update", object: Object, name: "x", oldValue: 1}
```
  There is also a `pairs` operator. This operator accepts an Object, and returns an Observable that emits, as key/value pairs, the attributes of that object. 

 #### Sample Code

 
```
var obj = {
  foo: 42,
  bar: 56,
  baz: 78
};

var source = Rx.Observable.pairs(obj);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });
```
 
```
Next: ['foo', 42]
Next: ['bar', 56]
Next: ['baz', 78]
Completed
```
  `pairs` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `fromArray fromIterator asObservable fromPromise`

       RxPHP implements this operator as `fromArray`. 

  Converts an array to an observable sequence 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/fromArray/fromArray.php

$source = \Rx\Observable::fromArray([1, 2, 3, 4]);

$subscription = $source->subscribe($stdoutObserver);

//Next value: 1
//Next value: 2
//Next value: 3
//Next value: 4
//Complete!
```
  
```
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Complete!
```
      RxPHP also has an operator `fromIterator`. 

  Converts an Iterator into an observable sequence 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/iterator/iterator.php

$generator = function () {
    for ($i = 1; $i <= 3; $i++) {
        yield $i;
    }

    return 4;
};

$source = Rx\Observable::fromIterator($generator());

$source->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Complete!
```
      RxPHP also has an operator `asObservable`. 

  Hides the identity of an observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/asObservable/asObservable.php

// Create subject
$subject = new \Rx\Subject\AsyncSubject();

// Send a value
$subject->onNext(42);
$subject->onCompleted();

// Hide its type
$source = $subject->asObservable();

$source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Complete!
```
      RxPHP also has an operator `fromPromise`. 

  Converts a promise into an observable 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/promise/fromPromise.php

$promise = \React\Promise\resolve(42);

$source = \Rx\Observable::fromPromise($promise);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Complete!
```
         ###  RxSwift `from toObservable`

    In Swift, this is implemented using the `Observable.from` class method.

 Each element of the array is produced as an emission. The difference between this method and `Observable.just` is that the latter emits the whole array as one emission.

 #### Sample Code

 
```
let numbers = [1,2,3,4,5]

let source = Observable.from(numbers)

source.subscribe {
    print($0)
}
```
  
```
next(1)
next(2)
next(3)
next(4)
next(5)
completed
```
     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/from.html>

Start
=====

 
> create an Observable that emits the return value of a function-like directive

  ![Start](http://reactivex.io/documentation/operators/images/start.c.png)  There are a number of ways that programming languages have for obtaining values as the result of calculations, with names like functions, futures, actions, callables, runnables, and so forth. The operators grouped here under the Start operator category make these things behave like Observables so that they can be chained with other Observables in an Observable cascade 

  See Also
--------

 * [From](from)
* [Just](just)
* [101 Rx Samples: Start — Run Code Asynchronously](http://rxwiki.wikidot.com/101samples#toc1)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `asyncAction asyncFunc deferFuture forEachFuture fromAction fromCallable fromFunc0 fromRunnable start startFuture toAsync`

     The various RxGroovy implementations of Start are found in the optional `rxjava-async` module. 

  ![start](http://reactivex.io/documentation/operators/images/start.png)  The `rxjava-async` module includes the `start` operator, which accepts a function as its parameter, calls that function to retrieve a value, and then returns an Observable that will emit that value to each subsequent observer. 


 Note that the function will only be executed once, even if more than one observer subscribes to the resulting Observable. 

   ![toAsync](http://reactivex.io/documentation/operators/images/toAsync.png)  The `rxjava-async` module also includes the `toAsync`, `asyncAction`, and `asyncFunc` operators. These accept a function or an Action as their parameter. In the case of a function, this variant of the operator calls that function to retrieve a value, and then returns an Observable that will emit that value to each subsequent observer (just as the `start` operator does). 


 In the case of Action, the process is similar, but there is no return value. In this case, the Observable created by this operator will emit a `null` before terminating. 


 Note that the function or Action will only be executed once, even if more than one observer subscribes to the resulting Observable. 

   ![startFuture](http://reactivex.io/documentation/operators/images/startFuture.png)  The `rxjava-async` module also includes the `startFuture` operator. You pass it a function that returns a `Future`. `startFuture` calls this function immediately to obtain the `Future`, and calls the `Future`’s `get` method to try to obtain its value. It returns an Observable to which it will emit this value to any subsequent observers. 

   ![deferFuture](http://reactivex.io/documentation/operators/images/deferFuture.png)  The `rxjava-async` module also includes the `deferFuture` operator. You pass it a function that returns a `Future` that returns an Observable. `deferFuture` returns an Observable, but does not call the function you provide until such time as an observer subscribes to the Observable it returns. When it does so, it immediately calls `get` on the resulting `Future`, and then mirrors the emissions from the Observable returned by the `Future` as its own emissions. 


 In this way you can include a `Future` that returns an Observable in a cascade of Observables as a peer to other Observables. 

   ![fromAction](http://reactivex.io/documentation/operators/images/fromAction.png)  The `rxjava-async` module also includes the `fromAction` operator. It accepts an `Action` as its parameter, and returns an Observable that emits the item you pass to `fromAction` upon termination of the `Action` 

   ![fromCallable](http://reactivex.io/documentation/operators/images/fromCallable.png)  The `rxjava-async` module also includes the `fromCallable` operator. It accepts a `Callable` as its parameter, and returns an Observable that emits the result of this callable as its sole emission. 

   ![fromRunnable](http://reactivex.io/documentation/operators/images/fromRunnable.png)  The `rxjava-async` module also includes the `fromRunnable` operator. It accepts a `Runnable` as its parameter, and returns an Observable that emits the item you pass to `fromRunnable` upon termination of the `Runnable` 

   ![forEachFuture](http://reactivex.io/documentation/operators/images/forEachFuture.png)  The `rxjava-async` module also includes the `forEachFuture` operator. It is not really a variant of the Start operator, but something all its own. You pass `forEachFuture` some subset of the typical observer methods (`onNext`, `onError`, and `onCompleted`) and the Observable will call these methods in the usual way. But `forEachFuture` itself returns a `Future` that blocks on `get` until the source Observable completes, then returns either the completion or error, depending on how the Observable completed. 


 You can use this if you need a function that blocks until the completion of an Observable. 

   The `rxjava-async` module also includes the `runAsync` operator. It is peculiar in that it creates a specialization of an Observable called a `StoppableObservable`. 


 Pass `runAsync` an `Action` and a [`Scheduler`](../scheduler), and it will return a `StoppableObservable` that uses the specified `Action` to generate items that it emits. The `Action` accepts an `Observer` and a `Subscription`. It uses the `Subscription` to check for the `unsubscribed` condition, upon which it will stop emitting items. You can also manually stop a `StoppableObservable` at any time by calling its `unsubscribe` method (which will also unsubscribe the `Subscription` you have associated with the `StoppableObservable`). 


 Because `runAsync` immediately invokes the `Action` and begins emitting the items (that is, it produces a *hot* Observable), it is possible that some items may be lost in the interval between when you establish the `StoppableObservable` with this operator and when your `Observer` is ready to receive items. If this is a problem, you can use the variant of `runAsync` that also accepts a `Subject` and pass a `ReplaySubject` with which you can retrieve the otherwise-missing items. 


 In RxGroovy there is also a version of the [From](from) operator that converts a `Future` into an Observable, and in this way resembles the Start operator. 

      ###  RxJava 1․x `asyncAction asyncFunc deferFuture forEachFuture fromAction fromCallable fromFunc0 fromRunnable start startFuture toAsync`

     The various RxJava implementations of Start are found in the optional `rxjava-async` module. 

  ![start](http://reactivex.io/documentation/operators/images/start.png)  The `rxjava-async` module includes the `start` operator, which accepts a function as its parameter, calls that function to retrieve a value, and then returns an Observable that will emit that value to each subsequent observer. 


 Note that the function will only be executed once, even if more than one observer subscribes to the resulting Observable. 

   ![toAsync](http://reactivex.io/documentation/operators/images/toAsync.png)  The `rxjava-async` module also includes the `toAsync`, `asyncAction`, and `asyncFunc` operators. These accept a function or an Action as their parameter. In the case of a function, this variant of the operator calls that function to retrieve a value, and then returns an Observable that will emit that value to each subsequent observer (just as the `start` operator does). 


 In the case of Action, the process is similar, but there is no return value. In this case, the Observable created by this operator will emit a `null` before terminating. 


 Note that the function or Action will only be executed once, even if more than one observer subscribes to the resulting Observable. 

   ![startFuture](http://reactivex.io/documentation/operators/images/startFuture.png)  The `rxjava-async` module also includes the `startFuture` operator. You pass it a function that returns a `Future`. `startFuture` calls this function immediately to obtain the `Future`, and calls the `Future`’s `get` method to try to obtain its value. It returns an Observable to which it will emit this value to any subsequent observers. 

   ![deferFuture](http://reactivex.io/documentation/operators/images/deferFuture.png)  The `rxjava-async` module also includes the `deferFuture` operator. You pass it a function that returns a `Future` that returns an Observable. `deferFuture` returns an Observable, but does not call the function you provide until such time as an observer subscribes to the Observable it returns. When it does so, it immediately calls `get` on the resulting `Future`, and then mirrors the emissions from the Observable returned by the `Future` as its own emissions. 


 In this way you can include a `Future` that returns an Observable in a cascade of Observables as a peer to other Observables. 

   ![fromAction](http://reactivex.io/documentation/operators/images/fromAction.png)  The `rxjava-async` module also includes the `fromAction` operator. It accepts an `Action` as its parameter, and returns an Observable that emits the item you pass to `fromAction` upon termination of the `Action` 

   ![fromCallable](http://reactivex.io/documentation/operators/images/fromCallable.png)  The `rxjava-async` module also includes the `fromCallable` operator. It accepts a `Callable` as its parameter, and returns an Observable that emits the result of this callable as its sole emission. 

   ![fromRunnable](http://reactivex.io/documentation/operators/images/fromRunnable.png)  The `rxjava-async` module also includes the `fromRunnable` operator. It accepts a `Runnable` as its parameter, and returns an Observable that emits the item you pass to `fromRunnable` upon termination of the `Runnable` 

   ![forEachFuture](http://reactivex.io/documentation/operators/images/forEachFuture.png)  The `rxjava-async` module also includes the `forEachFuture` operator. It is not really a variant of the Start operator, but something all its own. You pass `forEachFuture` some subset of the typical observer methods (`onNext`, `onError`, and `onCompleted`) and the Observable will call these methods in the usual way. But `forEachFuture` itself returns a `Future` that blocks on `get` until the source Observable completes, then returns either the completion or error, depending on how the Observable completed. 


 You can use this if you need a function that blocks until the completion of an Observable. 

   The `rxjava-async` module also includes the `runAsync` operator. It is peculiar in that it creates a specialization of an Observable called a `StoppableObservable`. 


 Pass `runAsync` an `Action` and a [`Scheduler`](../scheduler), and it will return a `StoppableObservable` that uses the specified `Action` to generate items that it emits. The `Action` accepts an `Observer` and a `Subscription`. It uses the `Subscription` to check for the `unsubscribed` condition, upon which it will stop emitting items. You can also manually stop a `StoppableObservable` at any time by calling its `unsubscribe` method (which will also unsubscribe the `Subscription` you have associated with the `StoppableObservable`). 


 Because `runAsync` immediately invokes the `Action` and begins emitting the items (that is, it produces a *hot* Observable), it is possible that some items may be lost in the interval between when you establish the `StoppableObservable` with this operator and when your `Observer` is ready to receive items. If this is a problem, you can use the variant of `runAsync` that also accepts a `Subject` and pass a `ReplaySubject` with which you can retrieve the otherwise-missing items. 


 In RxJava there is also a version of the [From](from) operator that converts a `Future` into an Observable, and in this way resembles the Start operator. 

      ###  RxJS `start startAsync toAsync`

     ![start](http://reactivex.io/documentation/operators/images/start.png)  RxJS implements the `start` operator. It takes as its parameters a function whose return value will be the emission from the resulting Observable, and, optionally, any additional parameter to that function and a [Scheduler](../scheduler) on which to run the function. 

 #### Sample Code

 
```
var context = { value: 42 };

var source = Rx.Observable.start(
    function () {
        return this.value;
    },
    context,
    Rx.Scheduler.timeout
);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 42
Completed
```
  `start` is found in the following distributions: 

 * `rx.async.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.async.compat.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

    ![start](http://reactivex.io/documentation/operators/images/startAsync.png)  RxJS also implements the `startAsync` operator. It takes as its parameters an asynchronous function whose return value will be the emission from the resulting Observable. 


 You can convert a function into an asynchronous function with the `toAsync` method. It takes a function, function parameter, and [Scheduler](../scheduler) as parameters, and returns an asynchronous function that will be invoked on the specified Scheduler. The last two parameters are optional; if you do not specify a Scheduler, the `timeout` Scheduler will be used by default. 

 #### Sample Code

 
```
var source = Rx.Observable.startAsync(function () {
    return RSVP.Promise.resolve(42);
});

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 42
Completed
```
  `startAsync` is found in the following distributions: 

 * `rx.async.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.async.compat.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.lite.js`
* `rx.lite.compat.js`

  `toAsync` is found in the following distributions: 

 * `rx.async.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)
* `rx.async.compat.js` (requires `rx.binding.js` and either `rx.js` or `rx.compat.js`)

        ###  RxPHP `start`

       RxPHP implements this operator as `start`. 

  Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/start/start.php

$source = Rx\Observable::start(function () {
    return 42;
});

$source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/start.html>

GroupBy
=======

 
> divide an Observable into a set of Observables that each emit a different subset of items from the original Observable

  ![GroupBy](http://reactivex.io/documentation/operators/images/groupBy.c.png)  The GroupBy operator divides an Observable that emits items into an Observable that emits Observables, each one of which emits some subset of the items from the original source Observable. Which items end up on which Observable is typically decided by a discriminating function that evaluates each item and assigns it a key. All items with the same key are emitted by the same Observable. 

  #### See Also

 * [Window](window)
* [Introduction to Rx: GroupBy](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#GroupBy)
* [Animations of Rx operators: GroupBy](http://blogs.microsoft.co.il/iblogger/2015/08/11/animations-of-rx-operators-groupby/) by Tamir Dresher

 Language-Specific Information
-----------------------------

    ###  RxGroovy `groupBy`

     ![groupBy](http://reactivex.io/documentation/operators/images/groupBy.png)  RxGroovy implements the `groupBy` operator. The Observable it returns emits items of a particular subclass of Observable — the `GroupedObservable`. Objects that implement the `GroupedObservable` interface have an additional method — `getkey` — by which you can retrieve the key by which items were designated for this particular `GroupedObservable`. 


 The following sample code uses `groupBy` to transform a list of numbers into two lists, grouped by whether or not the numbers are even: 

 #### Sample Code

 
```
def numbers = Observable.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
def groupFunc = { return(0 == (it % 2)); };

numbers.groupBy(groupFunc).flatMap({ it.reduce([it.getKey()], {a, b -> a << b}) }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
[false, 1, 3, 5, 7, 9]
[true, 2, 4, 6, 8]
Sequence complete
```
  Another version of `groupBy` allows you to pass in a transformative function that changes the elements before they are emitted by the resulting `GroupedObservable`s. 


 Note that when `groupBy` splits up the source Observable into an Observable that emits `GroupedObservable`s, each of these `GroupedObservable`s begins to buffer the items that it will emit upon subscription. For this reason, if you ignore any of these `GroupedObservable`s (you neither subscribe to it or apply an operator to it that subscribes to it), this buffer will present a potential memory leak. For this reason, rather than ignoring a `GroupedObservable` that you have no interest in observing, you should instead apply an operator like [`take(0)`](take) to it as a way of signalling to it that it may discard its buffer. 


 If you unsubscribe from one of the `GroupedObservable`s, or if an operator like `take` that you apply to the `GroupedObservable` unsubscribes from it, that `GroupedObservable` will be terminated. If the source Observable later emits an item whose key matches the `GroupedObservable` that was terminated in this way, `groupBy` will create and emit a *new* `GroupedObservable` to match the key. In other words, unsubscribing from a `GroupedObservable` will *not* cause `groupBy` to swallow items from its group. For example, see the following code: 

 #### Sample Code

 
```
Observable.range(1,5)
          .groupBy({ 0 })
          .flatMap({ this.take(1) })
          .subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
2
3
4
5
```
  In the above code, the source Observable emits the sequence `{ 1 2 3 4 5 }`. When it emits the first item in this sequence, the `groupBy` operator creates and emits a `GroupedObservable` with the key of `0`. The `flatMap` operator applies the `take(1)` operator to that `GroupedObservable`, which gives it the item (`1`) that it emits and that also unsubscribes from the `GroupedObservable`, which is terminated. When the source Observable emits the second item in its sequence, the `groupBy` operator creates and emits a *second* `GroupedObservable` with the same key (`0`) to replace the one that was terminated. `flatMap` again applies `take(1)` to this new `GroupedObservable` to retrieve the new item to emit (`2`) and to unsubscribe from and terminate the `GroupedObservable`, and this process repeats for the remaining items in the source sequence. 


 `groupBy` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`groupBy(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#groupBy(rx.functions.Func1))
* Javadoc: [`groupBy(Func1,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#groupBy(rx.functions.Func1,%20rx.functions.Func1))
       ###  RxJava 1․x `groupBy`

     ![groupBy](http://reactivex.io/documentation/operators/images/groupBy.png)  RxJava implements the `groupBy` operator. The Observable it returns emits items of a particular subclass of Observable — the `GroupedObservable`. Objects that implement the `GroupedObservable` interface have an additional method — `getkey` — by which you can retrieve the key by which items were designated for this particular `GroupedObservable`. 


 Another version of `groupBy` allows you to pass in a transformative function that changes the elements before they are emitted by the resulting `GroupedObservable`s. 


 Note that when `groupBy` splits up the source Observable into an Observable that emits `GroupedObservable`s, each of these `GroupedObservable`s begins to buffer the items that it will emit upon subscription. For this reason, if you ignore any of these `GroupedObservable`s (you neither subscribe to it or apply an operator to it that subscribes to it), this buffer will present a potential memory leak. For this reason, rather than ignoring a `GroupedObservable` that you have no interest in observing, you should instead apply an operator like [`take(0)`](take) to it as a way of signalling to it that it may discard its buffer. 


 If you unsubscribe from one of the `GroupedObservable`s, that `GroupedObservable` will be terminated. If the source Observable later emits an item whose key matches the `GroupedObservable` that was terminated in this way, `groupBy` will create and emit a new `GroupedObservable` to match the key. 


 `groupBy` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`groupBy(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#groupBy(rx.functions.Func1))
* Javadoc: [`groupBy(Func1,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#groupBy(rx.functions.Func1,%20rx.functions.Func1))
       ###  RxJS `groupBy groupByUntil`

     ![groupBy](http://reactivex.io/documentation/operators/images/groupBy.png)  RxJS implements `groupBy`. It takes one to three parameters: 

 1. (required) a function that accepts an item from the source Observable and returns its key
2. a function that accepts an item from the source Observable and returns an item to be emitted in its place by one of the resulting Observables
3. a function used to compare two keys for identity (that is, whether items with two keys should be emitted on the same Observable)

 #### Sample Code

 
```
var codes = [
    { keyCode: 38}, // up
    { keyCode: 38}, // up
    { keyCode: 40}, // down
    { keyCode: 40}, // down
    { keyCode: 37}, // left
    { keyCode: 39}, // right
    { keyCode: 37}, // left
    { keyCode: 39}, // right
    { keyCode: 66}, // b
    { keyCode: 65}  // a
];

var source = Rx.Observable.fromArray(codes)
    .groupBy(
        function (x) { return x.keyCode; },
        function (x) { return x.keyCode; });

var subscription = source.subscribe(
    function (obs) {
        // Print the count
        obs.count().subscribe(function (x) {
            console.log('Count: ' + x);
        });
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```


```
Count: 2
Count: 2
Count: 2
Count: 2
Count: 1
Count: 1
Completed
```
 `groupBy` is found in each of the following distributions:

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.coincidence.js`

    ![groupByUntil](http://reactivex.io/documentation/operators/images/groupByUntil.png)  RxJS also implements `groupByUntil`. It monitors an additional Observable, and whenever that Observable emits an item, it closes any of the keyed Observables it has opened (it will open new ones if additional items are emitted by the source Observable that match the key). `groupByUntil` takes from two to four parameters: 

 1. (required) a function that accepts an item from the source Observable and returns its key
2. a function that accepts an item from the source Observable and returns an item to be emitted in its place by one of the resulting Observables
3. (required) a function that returns an Observable, the emissions from which trigger the termination of any open Observables
4. a function used to compare two keys for identity (that is, whether items with two keys should be emitted on the same Observable)

 #### Sample Code

 
```
var codes = [
    { keyCode: 38}, // up
    { keyCode: 38}, // up
    { keyCode: 40}, // down
    { keyCode: 40}, // down
    { keyCode: 37}, // left
    { keyCode: 39}, // right
    { keyCode: 37}, // left
    { keyCode: 39}, // right
    { keyCode: 66}, // b
    { keyCode: 65}  // a
];

var source = Rx.Observable
    .for(codes, function (x) { return Rx.Observable.return(x).delay(1000); })
    .groupByUntil(
        function (x) { return x.keyCode; },
        function (x) { return x.keyCode; },
        function (x) { return Rx.Observable.timer(2000); });

var subscription = source.subscribe(
    function (obs) {
        // Print the count
        obs.count().subscribe(function (x) { console.log('Count: ' + x); });
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```


```
Count: 2
Count: 2
Count: 1
Count: 1
Count: 1
Count: 1
Count: 1
Count: 1
Completed
```
 `groupByUntil` is found in each of the following distributions:

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.coincidence.js`

        ###  RxPHP `groupBy groupByUntil partition`

       RxPHP implements this operator as `groupBy`. 

  Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/groupBy/groupBy.php

$observable = \Rx\Observable::fromArray([21, 42, 21, 42, 21, 42]);
$observable
    ->groupBy(
        function ($elem) {
            if ($elem === 42) {
                return 0;
            }

            return 1;
        },
        null,
        function ($key) {
            return $key;
        }
    )
    ->subscribe(function ($groupedObserver) use ($createStdoutObserver) {
        $groupedObserver->subscribe($createStdoutObserver($groupedObserver->getKey() . ": "));
    });
```
  
```
1: Next value: 21
0: Next value: 42
1: Next value: 21
0: Next value: 42
1: Next value: 21
0: Next value: 42
1: Complete!
0: Complete!
```
      RxPHP also has an operator `groupByUntil`. 

  Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/groupBy/groupByUntil.php

$codes = [
    ['id' => 38],
    ['id' => 38],
    ['id' => 40],
    ['id' => 40],
    ['id' => 37],
    ['id' => 39],
    ['id' => 37],
    ['id' => 39],
    ['id' => 66],
    ['id' => 65]
];

$source = Rx\Observable
    ::fromArray($codes)
    ->concatMap(function ($x) {
        return \Rx\Observable::timer(100)->mapTo($x);
    })
    ->groupByUntil(
        function ($x) {
            return $x['id'];
        },
        function ($x) {
            return $x['id'];
        },
        function ($x) {
            return Rx\Observable::timer(200);
        });

$subscription = $source->subscribe(new CallbackObserver(
    function (\Rx\Observable $obs) {
        // Print the count
        $obs->count()->subscribe(new CallbackObserver(
            function ($x) {
                echo 'Count: ', $x, PHP_EOL;
            }));
    },
    function (Throwable $err) {
        echo 'Error', $err->getMessage(), PHP_EOL;
    },
    function () {
        echo 'Completed', PHP_EOL;
    }));
```
  
```
Count: 2
Count: 2
Count: 1
Count: 1
Count: 1
Count: 1
Count: 1
Count: 1
Completed
```
      RxPHP also has an operator `partition`. 

  Returns two observables which partition the observations of the source by the given function. The first will trigger observations for those values for which the predicate returns true. The second will trigger observations for those values where the predicate returns false. The predicate is executed once for each subscribed observer. Both also propagate all error observations arising from the source and each completes when the source completes. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/partition/partition.php

list($evens, $odds) = \Rx\Observable::range(0, 10, \Rx\Scheduler::getImmediate())
    ->partition(function ($x) {
        return $x % 2 === 0;
    });

//Because we used the immediate scheduler with range, the subscriptions are not asynchronous.
$evens->subscribe($createStdoutObserver('Evens '));
$odds->subscribe($createStdoutObserver('Odds '));
```
  
```
Evens Next value: 0
Evens Next value: 2
Evens Next value: 4
Evens Next value: 6
Evens Next value: 8
Evens Complete!
Odds Next value: 1
Odds Next value: 3
Odds Next value: 5
Odds Next value: 7
Odds Next value: 9
Odds Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/groupby.html>

IgnoreElements
==============

 
> do not emit any items from an Observable but mirror its termination notification

  ![IgnoreElements](http://reactivex.io/documentation/operators/images/ignoreElements.c.png)  The IgnoreElements operator suppresses all of the items emitted by the source Observable, but allows its termination notification (either `onError` or `onCompleted`) to pass through unchanged. 


 If you do not care about the items being emitted by an Observable, but you do want to be notified when it completes or when it terminates with an error, you can apply the `ignoreElements` operator to the Observable, which will ensure that it will never call its observers’ `onNext` handlers. 

  #### See Also

 * [Introduction to Rx: IgnoreElements](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#IgnoreElements)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `ignoreElements`

     ![ignoreElements](http://reactivex.io/documentation/operators/images/ignoreElements.png)  RxGroovy implements this operator as `ignoreElements`. 

 * Javadoc: [`ignoreElements()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#ignoreElements())
   `ignoreElements` does not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJava 1․x `ignoreElements`

     ![ignoreElements](http://reactivex.io/documentation/operators/images/ignoreElements.png)  RxJava implements this operator as `ignoreElements`. 

 * Javadoc: [`ignoreElements()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#ignoreElements())
   `ignoreElements` does not by default operate on any particular [Scheduler](../scheduler). 

      ###  RxJS `ignoreElements`

     ![ignoreElements](http://reactivex.io/documentation/operators/images/ignoreElements.png)  RxJS implements this operator as `ignoreElements`. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 10)
    .ignoreElements();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Completed
```
  `ignoreElements` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/ignoreelements.html>

And/Then/When
=============

 
> combine sets of items emitted by two or more Observables by means of Pattern and Plan intermediaries

  ![And/Then/When](http://reactivex.io/documentation/operators/images/and_then_when.C.png)  The combination of the And, Then, and When operators behave much like the Zip operator, but they do so by means of intermediate data structures. And accepts two or more Observables and combines the emissions from each, one set at a time, into `Pattern` objects. Then operates on such `Pattern` objects, transforming them in a `Plan`. When in turn transforms these various `Plan` objects into emissions from an Observable. 

  #### See Also

 * [Zip](zip)
* [Introduction to Rx: And-Then-When](http://www.introtorx.com/content/v1.0.10621.0/12_CombiningSequences.html#AndThenWhen)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `and then when`

     ![and/then/when](http://reactivex.io/documentation/operators/images/and_then_when.png)  In RxGroovy, these are not part of the core ReactiveX implementation, but are found as `and`, `then`, and `when` in the `rxjava-joins` module. 

       ###  RxJava 1․x `and then when`

     ![and/then/when](http://reactivex.io/documentation/operators/images/and_then_when.png)  These are not part of the core RxJava implementation, but are found as `and`, `then`, and `when` in the `rxjava-joins` module. 

       ###  RxJS `and thenDo when`

     ![and/thenDo/when](http://reactivex.io/documentation/operators/images/and_thenDo_when.png)  RxJS implements these operators as `and`, `thenDo`, and `when`. 


 These are found in the following packages: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.joinpatterns.js`

  They require one of the following packages: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/and-then-when.html>

CombineLatest
=============

 
> when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#combineLatest)  The CombineLatest operator behaves in a similar way to Zip, but while Zip emits items only when *each* of the zipped source Observables have emitted a previously unzipped item, CombineLatest emits an item whenever *any* of the source Observables emits an item (so long as each of the source Observables has emitted at least one item). When any of the source Observables emits an item, CombineLatest combines the most recently emitted items from each of the other source Observables, using a function you provide, and emits the return value from that function. 

  #### See Also

 * [Zip](zip)
* [Introduction to Rx: CombineLatest](http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#CombineLatest)
* [RxMarbles: `combineLatest`](http://rxmarbles.com/#combineLatest)
* [RxMarbles: `withLatestFrom`](http://rxmarbles.com/#withLatestFrom)
* [101 Rx Samples: CombineLatest — Parallel Execution](http://rxwiki.wikidot.com/101samples#toc3)
* [101 Rx Samples: CombineLatest](http://rxwiki.wikidot.com/101samples#toc50)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `combineLatest withLatestFrom`

     ![combineLatest](http://reactivex.io/documentation/operators/images/combineLatest.png)  RxGroovy implements this operator as `combineLatest`. It may take between two and nine Observables (as well as the combining function) as parameters, or a single `List` of Observables (as well as the combining function). It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`combineLatest(List,FuncN)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#combineLatest(java.util.List,%20rx.functions.FuncN))
* Javadoc: [`combineLatest(Observable,Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#combineLatest(rx.Observable,%20rx.Observable,%20rx.functions.Func2)) (there are also versions that take up to nine Observables)
   ![withLatestFrom](http://reactivex.io/documentation/operators/images/withLatestFrom.png)  Under development, but not part of the 1.0 release, is the `withLatestFrom` operator. It is similar to `combineLatest`, but only emits items when the single source Observable emits an item (not when *any* of the Observables that are passed to the operator do, as `combineLatest` does). 

       ###  RxJava 1․x `combineLatest withLatestFrom`

     ![combineLatest](http://reactivex.io/documentation/operators/images/combineLatest.png)  RxJava implements this operator as `combineLatest`. It may take between two and nine Observables (as well as the combining function) as parameters, or a single `List` of Observables (as well as the combining function). It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`combineLatest(List,FuncN)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#combineLatest(java.util.List,%20rx.functions.FuncN))
* Javadoc: [`combineLatest(Observable,Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#combineLatest(rx.Observable,%20rx.Observable,%20rx.functions.Func2)) (there are also versions that take up to nine Observables)
   ![withLatestFrom](http://reactivex.io/documentation/operators/images/withLatestFrom.png)  Under development, but not part of the 1.0 release, is the `withLatestFrom` operator. It is similar to `combineLatest`, but only emits items when the single source Observable emits an item (not when *any* of the Observables that are passed to the operator do, as `combineLatest` does). 

       ###  RxJS `combineLatest withLatestFrom`

     ![combineLatest](http://reactivex.io/documentation/operators/images/combineLatest.png)  RxJS implements this operator as `combineLatest`. It may take a variable number of individual Observables (as well as the combining function) as parameters, or a single `Array` of Observables (as well as the combining function). 

 #### Sample Code

 
```
/* Have staggering intervals */
var source1 = Rx.Observable.interval(100)
    .map(function (i) { return 'First: ' + i; });

var source2 = Rx.Observable.interval(150)
    .map(function (i) { return 'Second: ' + i; });

// Combine latest of source1 and source2 whenever either gives a value
var source = source1.combineLatest(
        source2,
        function (s1, s2) { return s1 + ', ' + s2; }
    ).take(4);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x.toString());
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: First: 0, Second: 0
Next: First: 1, Second: 0
Next: First: 1, Second: 1
Next: First: 2, Second: 1
Completed
```
    ![withLatestFrom](http://reactivex.io/documentation/operators/images/withLatestFrom.png)  RxJS also has a `withLatestFrom` operator. It is similar to `combineLatest`, but only emits items when the single source Observable emits an item (not when *any* of the Observables that are passed to the operator do, as `combineLatest` does). 

 #### Sample Code

 
```
/* Have staggering intervals */
var source1 = Rx.Observable.interval(140)
    .map(function (i) { return 'First: ' + i; });

var source2 = Rx.Observable.interval(50)
    .map(function (i) { return 'Second: ' + i; });

// When source1 emits a value, combine it with the latest emission from source2.
var source = source1.withLatestFrom(
    source2,
    function (s1, s2) { return s1 + ', ' + s2; }
).take(4);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x.toString());
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: First: 0, Second: 1
Next: First: 1, Second: 4
Next: First: 2, Second: 7
Next: First: 3, Second: 10
Completed
```
    These two operators are both available in each of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `combineLatest withLatestFrom`

       RxPHP implements this operator as `combineLatest`. 

  Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. Observables need to be an array. If the result selector is omitted, a list with the elements will be yielded. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/combineLatest/combineLatest.php

/* Have staggering intervals */
$source1 = \Rx\Observable::interval(100);
$source2 = \Rx\Observable::interval(120);

$source = $source1->combineLatest([$source2], function ($value1, $value2) {
    return "First: {$value1}, Second: {$value2}";
})->take(4);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: First: 0, Second: 0
Next value: First: 1, Second: 0
Next value: First: 1, Second: 1
Next value: First: 2, Second: 1
Complete!
```
      RxPHP also has an operator `withLatestFrom`. 

  Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/withLatestFrom/withLatestFrom.php

/* Have staggering intervals */
$source1 = \Rx\Observable::interval(140)
    ->map(function ($i) {
        return 'First: ' . $i;
    });
$source2 = \Rx\Observable::interval(50)
    ->map(function ($i) {
        return 'Second: ' . $i;
    });

$source3 = \Rx\Observable::interval(100)
    ->map(function ($i) {
        return 'Third: ' . $i;
    });

$source = $source1->withLatestFrom([$source2, $source3], function ($value1, $value2, $value3) {
    return $value1 . ', ' . $value2 . ', ' . $value3;
})->take(4);

$source->subscribe($stdoutObserver);
```
  
```
Next value: First: 0, Second: 1, Third: 0
Next value: First: 1, Second: 4, Third: 1
Next value: First: 2, Second: 7, Third: 3
Next value: First: 3, Second: 10, Third: 4
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/combinelatest.html>

Join
====

 
> combine items emitted by two Observables whenever an item from one Observable is emitted during a time window defined according to an item emitted by the other Observable

  ![Join](http://reactivex.io/documentation/operators/images/join.c.png)  The `Join` operator combines the items emitted by two Observables, and selects which items to combine based on duration-windows that you define on a per-item basis. You implement these windows as Observables whose lifespans begin with each item emitted by either Observable. When such a window-defining Observable either emits an item or completes, the window for the item it is associated with closes. So long as an item’s window is open, it will combine with any item emitted by the other Observable. You define the function by which the items combine. 

   ![GroupJoin](http://reactivex.io/documentation/operators/images/groupJoin.c.png)  Most ReactiveX implementations that have a `Join` operator also have a `GroupJoin` operator that is similar, except that the function you define to combine items emitted by the two Observables pairs individual items emitted by the source Observable not with an item from the second Observable, but with an Observable that emits items from the second Observable that fall in the same window. 

  #### See Also

 * [CombineLatest](combinelatest)
* [Zip](zip)
* [Introduction to Rx: Join](http://www.introtorx.com/Content/v1.0.10621.0/17_SequencesOfCoincidence.html#Join)
* [Introduction to Rx: GroupJoin](http://www.introtorx.com/Content/v1.0.10621.0/17_SequencesOfCoincidence.html#GroupJoin)
* [101 Rx Samples: GroupJoin — Joins two streams by matching by one of their attributes](http://rxwiki.wikidot.com/101samples#toc39)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `join groupJoin`

     ![join](http://reactivex.io/documentation/operators/images/join_.png)  The `join` operator takes four parameters: 

 1. the second Observable to combine with the source Observable
2. a function that accepts an item from the source Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the second Observable
3. a function that accepts an item from the second Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the first Observable
4. a function that accepts an item from the first Observable and an item from the second Observable and returns an item to be emitted by the Observable returned from `join`

  `join` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`Join(Observable,Func1,Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#join(rx.Observable,%20rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func2))
   ![join](http://reactivex.io/documentation/operators/images/groupJoin.png)  The `groupJoin` operator takes four parameters: 

 1. the second Observable to combine with the source Observable
2. a function that accepts an item from the source Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the second Observable
3. a function that accepts an item from the second Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the first Observable
4. a function that accepts an item from the first Observable and an Observable that emits items from the second Observable and returns an item to be emitted by the Observable returned from `groupJoin`

  `groupJoin` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`groupJoin(Observable,Func1,Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#groupJoin(rx.Observable,%20rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func2))
   ![join](http://reactivex.io/documentation/operators/images/St.join.png)  Note that there is also a `join` operator in the optional `StringObservable` class. It converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all, separating them by a specified string delimiter. 

       ###  RxJava 1․x `join groupJoin`

     ![join](http://reactivex.io/documentation/operators/images/join_.png)  The `join` operator takes four parameters: 

 1. the second Observable to combine with the source Observable
2. a function that accepts an item from the source Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the second Observable
3. a function that accepts an item from the second Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the first Observable
4. a function that accepts an item from the first Observable and an item from the second Observable and returns an item to be emitted by the Observable returned from `join`

  `join` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`Join(Observable,Func1,Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#join(rx.Observable,%20rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func2))
   ![join](http://reactivex.io/documentation/operators/images/groupJoin.png)  The `groupJoin` operator takes four parameters: 

 1. the second Observable to combine with the source Observable
2. a function that accepts an item from the source Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the second Observable
3. a function that accepts an item from the second Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the first Observable
4. a function that accepts an item from the first Observable and an Observable that emits items from the second Observable and returns an item to be emitted by the Observable returned from `groupJoin`

  `groupJoin` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`groupJoin(Observable,Func1,Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#groupJoin(rx.Observable,%20rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func2))
   ![join](http://reactivex.io/documentation/operators/images/St.join.png)  Note that there is also a `join` operator in the optional `StringObservable` class. It converts an Observable that emits a sequence of strings into an Observable that emits a single string that concatenates them all, separating them by a specified string delimiter. 

       ###  RxJS `join groupJoin`

     ![join](http://reactivex.io/documentation/operators/images/join_.png)  The `join` operator takes four parameters: 

 1. the second Observable to combine with the source Observable
2. a function that accepts an item from the source Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the second Observable
3. a function that accepts an item from the second Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the first Observable
4. a function that accepts an item from the first Observable and an item from the second Observable and returns an item to be emitted by the Observable returned from `join`

 #### Sample Code

 
```
var xs = Rx.Observable.interval(100)
    .map(function (x) { return 'first' + x; });

var ys = Rx.Observable.interval(100)
    .map(function (x) { return 'second' + x; });

var source = xs
    .join(
        ys,
        function () { return Rx.Observable.timer(0); },
        function () { return Rx.Observable.timer(0); },
        function (x, y) { return x + y; }
    )
    .take(5);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: first0second0
Next: first1second1
Next: first2second2
Next: first3second3
Next: first4second4
Completed
```
    ![join](http://reactivex.io/documentation/operators/images/groupJoin.png)  The `groupJoin` operator takes four parameters: 

 1. the second Observable to combine with the source Observable
2. a function that accepts an item from the source Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the second Observable
3. a function that accepts an item from the second Observable and returns an Observable whose lifespan governs the duration during which that item will combine with items from the first Observable
4. a function that accepts an item from the first Observable and an Observable that emits items from the second Observable and returns an item to be emitted by the Observable returned from `groupJoin`

 #### Sample Code

 
```
ar xs = Rx.Observable.interval(100)
    .map(function (x) { return 'first' + x; });

var ys = Rx.Observable.interval(100)
    .map(function (x) { return 'second' + x; });

var source = xs.groupJoin(
    ys,
    function () { return Rx.Observable.timer(0); },
    function () { return Rx.Observable.timer(0); },
    function (x, yy) {
        return yy.select(function (y) {
            return x + y;
        })
    }).mergeAll().take(5);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: first0second0
Next: first1second1
Next: first2second2
Next: first3second3
Next: first4second4
Completed
```
    `join` and `groupJoin` are found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.coincidence.js`

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/join.html>

FlatMap
=======

 
> transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

  ![FlatMap](http://reactivex.io/documentation/operators/images/flatMap.c.png)  The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items. FlatMap then merges the emissions of these resulting Observables, emitting these merged results as its own sequence. 


 This method is useful, for example, when you have an Observable that emits a series of items that themselves have Observable members or are in other ways transformable into Observables, so that you can create a new Observable that emits the complete collection of items emitted by the sub-Observables of these items. 


 Note that FlatMap *merges* the emissions of these Observables, so that they may interleave. 


 In several of the language-specific implementations there is also an operator that does *not* interleave the emissions from the transformed Observables, but instead emits these emissions in strict order, often called ConcatMap or something similar. 

  #### See Also

 * [Map](map)
* [Grokking RxJava: Operator, Operator](http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2/) by Dan Lew
* [Introduction to Rx: SelectMany](http://www.introtorx.com/Content/v1.0.10621.0/08_Transformation.html#SelectMany)
* [Recursive Observables with RxJava](http://jschneider.io/2014/11/26/Recursive-Observables-with-Rx-Java.html) by Jon Schneider
* [RxJava Observable transformation: concatMap() vs. flatMap()](http://fernandocejas.com/2015/01/11/rxjava-observable-tranformation-concatmap-vs-flatmap/) by Fernando Cejas

 Language-Specific Information
-----------------------------

    ###  RxGroovy `concatMap flatMap flatMapIterable StringObservable.split switchMap`

     ![flatMap](http://reactivex.io/documentation/operators/images/mergeMap.png)  RxGroovy implements the `flatMap` operator. 

 #### Sample Code

 
```
// this closure is an Observable that emits three numbers
numbers   = Observable.from([1, 2, 3]);
// this closure is an Observable that emits two numbers based on what number it is passed
multiples = { n -> Observable.from([ n*2, n*3 ]) };

numbers.flatMap(multiples).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
2
3
4
6
6
9
Sequence complete
```
  Note that if any of the individual Observables mapped to the items from the source Observable by `flatMap` aborts by invoking `onError`, the Observable produced by `flatMap` will itself immediately abort and invoke `onError`. 


 A version of this variant of the operator (still in Beta as of this writing) takes an additional `int` parameter. This parameter sets the maximum number of concurrent subscriptions that `flatMap` will attempt to have to the Observables that the items emitted by the source Observable map to. When it reaches this maximum number, it will wait for one of those Observables to terminate before subscribing to another. 

 * Javadoc: [`flatMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1))
* Javadoc: [`flatMap(Func1,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20int))
   ![flatMap](http://reactivex.io/documentation/operators/images/mergeMap.nce.png)  Another version of `flatMap` creates (and flattens) a new Observable for each item *and notification* from the source Observable. 


 A version of this variant of the operator (still in Beta as of this writing) takes an additional `int` parameter. This parameter sets the maximum number of concurrent subscriptions that `flatMap` will attempt to have to the Observables that the items emitted by the source Observable map to. When it reaches this maximum number, it will wait for one of those Observables to terminate before subscribing to another. 

 * Javadoc: [`flatMap(Func1,Func1,Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0))
* Javadoc: [`flatMap(Func1,Func1,Func0,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0,%20int))
   ![flatMap](http://reactivex.io/documentation/operators/images/mergeMap.r.png)  Another version combines items from the source Observable with the Observable triggered by those source items, and emits these combinations. 


 A version of this variant of the operator (still in Beta as of this writing) takes an additional `int` parameter. This parameter sets the maximum number of concurrent subscriptions that `flatMap` will attempt to have to the Observables that the items emitted by the source Observable map to. When it reaches this maximum number, it will wait for one of those Observables to terminate before subscribing to another. 

 * Javadoc: [`flatMap(Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func2))
* Javadoc: [`flatMap(Func1,Func2,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func2,%20int))
   ![flatMapIterable](http://reactivex.io/documentation/operators/images/mergeMapIterable.png)  The `flatMapIterable` variants pair up source items and generated `Iterable`s rather than source items and generated Observables, but otherwise work in much the same way. 

 * Javadoc: [`flatMapIterable(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMapIterable(rx.functions.Func1))
* Javadoc: [`flatMapIterable(Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMapIterable(rx.functions.Func1,%20rx.functions.Func2))
   ![concatMap](http://reactivex.io/documentation/operators/images/concatMap.png)  There is also a `concatMap` operator, which is like the simpler version of the `flatMap` operator, but it concatenates rather than merges the resulting Observables in order to generate its own sequence. 

 * Javadoc: [`concatMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concatMap(rx.functions.Func1))
   ![switchMap](http://reactivex.io/documentation/operators/images/switchMap.png)  RxGroovy also implements the `switchMap` operator. It behaves much like `flatMap`, except that whenever a new item is emitted by the source Observable, it will unsubscribe to and stop mirroring the Observable that was generated from the previously-emitted item, and begin only mirroring the current one. 

 * Javadoc: [`switchMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#switchMap(rx.functions.Func1))
   ![split](http://reactivex.io/documentation/operators/images/St.split.png)  In the distinct `StringObservable` class (not part of RxGroovy by default) there is also a `split` operator that converts an Observable of Strings into an Observable of Strings that treats the source sequence as a stream and splits it on a specified regex boundary, then merges the results of this split. 

 #### See Also

 * [Aligning packets with JSON documents](http://www.nurkiewicz.com/2014/12/accessing-meetups-streaming-api-with.html) with the `split` operator

        ###  RxJava 1․x `concatMap flatMap flatMapIterable StringObervable.split switchMap`

     ![flatMap](http://reactivex.io/documentation/operators/images/mergeMap.png)  RxJava implements the `flatMap` operator. 


 Note that if any of the individual Observables mapped to the items from the source Observable by `flatMap` aborts by invoking `onError`, the Observable produced by `flatMap` will itself immediately abort and invoke `onError`. 


 A version of this variant of the operator (still in Beta as of this writing) takes an additional `int` parameter. This parameter sets the maximum number of concurrent subscriptions that `flatMap` will attempt to have to the Observables that the items emitted by the source Observable map to. When it reaches this maximum number, it will wait for one of those Observables to terminate before subscribing to another. 

 * Javadoc: [`flatMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1))
* Javadoc: [`flatMap(Func1,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20int))
   ![flatMap](http://reactivex.io/documentation/operators/images/mergeMap.nce.png)  Another version of `flatMap` creates (and flattens) a new Observable for each item *and notification* from the source Observable. 


 A version of this variant of the operator (still in Beta as of this writing) takes an additional `int` parameter. This parameter sets the maximum number of concurrent subscriptions that `flatMap` will attempt to have to the Observables that the items emitted by the source Observable map to. When it reaches this maximum number, it will wait for one of those Observables to terminate before subscribing to another. 

 * Javadoc: [`flatMap(Func1,Func1,Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0))
* Javadoc: [`flatMap(Func1,Func1,Func0,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0,%20int))
   ![flatMap](http://reactivex.io/documentation/operators/images/mergeMap.r.png)  Another version combines items from the source Observable with the Observable triggered by those source items, and emits these combinations. 


 A version of this variant of the operator (still in Beta as of this writing) takes an additional `int` parameter. This parameter sets the maximum number of concurrent subscriptions that `flatMap` will attempt to have to the Observables that the items emitted by the source Observable map to. When it reaches this maximum number, it will wait for one of those Observables to terminate before subscribing to another. 

 * Javadoc: [`flatMap(Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func2))
* Javadoc: [`flatMap(Func1,Func2,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMap(rx.functions.Func1,%20rx.functions.Func2,%20int))
   ![flatMapIterable](http://reactivex.io/documentation/operators/images/mergeMapIterable.png)  The `flatMapIterable` variants pair up source items and generated `Iterable`s rather than source items and generated Observables, but otherwise work in much the same way. 

 * Javadoc: [`flatMapIterable(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMapIterable(rx.functions.Func1))
* Javadoc: [`flatMapIterable(Func1,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#flatMapIterable(rx.functions.Func1,%20rx.functions.Func2))
   ![concatMap](http://reactivex.io/documentation/operators/images/concatMap.png)  There is also a `concatMap` operator, which is like the simpler version of the `flatMap` operator, but it concatenates rather than merges the resulting Observables in order to generate its own sequence. 

 * Javadoc: [`concatMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concatMap(rx.functions.Func1))
   ![switchMap](http://reactivex.io/documentation/operators/images/switchMap.png)  RxJava also implements the `switchMap` operator. It behaves much like `flatMap`, except that whenever a new item is emitted by the source Observable, it will unsubscribe to and stop mirroring the Observable that was generated from the previously-emitted item, and begin only mirroring the current one. 

 * Javadoc: [`switchMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#switchMap(rx.functions.Func1))
   ![split](http://reactivex.io/documentation/operators/images/St.split.png)  In the distinct `StringObservable` class (not part of RxJava by default) there is also a `split` operator that converts an Observable of Strings into an Observable of Strings that treats the source sequence as a stream and splits it on a specified regex boundary, then merges the results of this split. 

       ###  RxJS `concatMap concatMapObserver flatMap flatMapFirst flatMapLatest flatMapObserver flatMapWithMaxConcurrency for forIn manySelect selectConcat selectConcatObserver selectMany selectManyObserver selectSwitch selectSwitchFirst selectWithMatchConcurrent switchMap`

     RxJS has a wealth of operators that perform FlatMap-like operations. In RxJS, the functions that transform items emitted by the source Observable into Observables typically take as parameters both the item and the index of the item in the Observable sequence. 

  ![flatMap](http://reactivex.io/documentation/operators/images/flatMap.png)  RxJS implements the basic `flatMap` operator. It has a variant that allows you to apply a transformative function (an optional second parameter to `flatMap`) to the items emitted by the Observables generated for each item in the source Observable, before merging and emitting those items. 


 `flatMap` works just as well if the function you provide transforms items from the source Observables into Observables, into Promises, or into arrays. 


 “`selectMany`” is an alias for `flatMap`. 

 #### Sample Code

 
```
var source = Rx.Observable
    .range(1, 2)
    .selectMany(function (x) {
        return Rx.Observable.range(x, 2);
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 1
Next: 2
Next: 2
Next: 3
Completed
```
 
```
// Using a promise
var source = Rx.Observable.of(1,2,3,4)
    .selectMany(function (x, i) {
        return Promise.resolve(x + i);
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 1
Next: 3
Next: 5
Next: 7
Completed
```
 
```
// Using an array
Rx.Observable.of(1,2,3)
  .flatMap(
    function (x, i) { return [x,i]; },
    function (x, y, ix, iy) { return x + y + ix + iy; }
  );

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 2
Next: 2
Next: 5
Next: 5
Next: 8
Next: 8
Completed
```
 `flatMap` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![flatMapLatest](http://reactivex.io/documentation/operators/images/flatMapLatest.png)  The `flatMapLatest` operator behaves much like the standard FlatMap operator, except that whenever a new item is emitted by the source Observable, it will unsubscribe to and stop mirroring the Observable that was generated from the previously-emitted item, and begin only mirroring the current one. 


 “`selectSwitch`” is an alias for `flatMapLatest`. 

 #### Sample Code

 
```
var source = Rx.Observable
    .range(1, 2)
    .flatMapLatest(function (x) {
        return Rx.Observable.range(x, 2);
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 1
Next: 2
Next: 3
Completed
```
 `flatMapLatest` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![flatMapObserver](http://reactivex.io/documentation/operators/images/flatMapObserver.png)  `flatMapObserver` creates (and flattens) a new Observable for each item *and notification* from the source Observable. It accepts a different transformation function to respond to `onNext`, `onError`, and `onCompleted` notifications and to return an Observable for each. 


 “`selectManyObserver`” is an alias for `flatMapObserver`. 

 #### Sample Code

 
```
var source = Rx.Observable.range(1, 3)
    .flatMapObserver(
        function (x, i) {
            return Rx.Observable.repeat(x, i);
        },
        function (err) {
            return Rx.Observable.return(42);
        },
        function () {
            return Rx.Observable.empty();
        });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```


```
Next: 2
Next: 3
Next: 3
Completed
```
 `flatMapObserver` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`

    ![concatMap](http://reactivex.io/documentation/operators/images/concatMap.png)  There is also a `concatMap` operator, which is like the `flatMap` operator, but it concatenates rather than merges the resulting Observables in order to generate its own sequence. 


 As with `flatMap`, `concatMap` works just as well if the function you provide transforms items from the source Observables into Observables, into Promises, or into arrays. 

 “`selectConcat`” is an alias for `concatMap`.

 `concatMap` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![for](http://reactivex.io/documentation/operators/images/for.png)  The `for` operator (and its alias, `forIn`) is very similar to `concatMap`, though it has a converse flexibility. While `concatMap` operates on an Observable source and can use Observable, Promise, or array intermediaries to generate its output sequence; `for` always uses Observables as its intermediaries, but can operate on a source that is either an Observable, a Promise, or an array. 

 `concatMap` is found in each of the following distributions:

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.experimental.js` (requires either `rx.js`, `rx.compat.js`, `rx.lite.js`, or `rx.lite.compat.js`)

    ![concatMapObserver](http://reactivex.io/documentation/operators/images/concatMapObserver.png)  There is also a `concatMapObserver` operator, which is like the `flatMapObserver` operator, in that it creates Observables to merge from both the emissions and terminal notifications of the source Observable, but it concatenates rather than merges these resulting Observables in order to generate its own sequence. 


 “`selectConcatObserver`” is an alias for `concatMapObserver`. 

 `concatMapObserver` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`

    ![manySelect](http://reactivex.io/documentation/operators/images/manySelect.png)  The `manySelect` operator is often described as a “comonadic bind.” If that clears things up for you, you’re welcome. Elsewise, here’s an explanation: 


 `manySelect` internally transforms each item emitted by the source Observable into an Observable that emits that item and all items subsequently emitted by the source Observable, in the same order. So, for example, it internally transforms an Observable that emits the numbers 1,2,3 into three Observables: one that emits 1,2,3, one that emits 2,3, and one that emits 3. 


 Then `manySelect` passes each of these Observables into a function that you provide, and emits, as the emissions from the Observable that `manySelect` returns, the return values from those function calls. 


 In this way, each item emitted by the resulting Observable is a function of the corresponding item in the source Observable and all of the items emitted by the source Observable after it. 


 `manySelect` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.experimental.js`

  `manySelect` requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

 #### See Also

 * [Microsoft Developer Network: “What does the new ManySelect operator do?”](https://social.msdn.microsoft.com/Forums/en-US/e70fe8b6-6d9d-486a-a8d0-c1bc66551ded/what-does-the-new-manyselect-operator-do?forum=rx)

        ###  RxPHP `flatMap flatMapTo selectMany flatMapLatest concatMap concatMapTo`

       RxPHP implements this operator as `flatMap`. 

  Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/flatMap/flatMap.php

$observable = Rx\Observable::range(1, 2);

$selectManyObservable = $observable->flatMap(function ($value) {
    return Rx\Observable::range($value, 2);
});

$selectManyObservable->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Next value: 2
Next value: 3
Complete!
```
      RxPHP also has an operator `flatMapTo`. 

  Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/concat/concatMapTo.php

$obs = \Rx\Observable::interval(100)
    ->take(3)
    ->mapWithIndex(function ($i) {
        return $i;
    });

$source = Rx\Observable::range(0, 5)
    ->concatMapTo($obs);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Next value: 5
Next value: 6
Next value: 7
Next value: 8
Next value: 9
Next value: 10
Next value: 11
Next value: 12
Next value: 13
Next value: 14
Complete!
```
      RxPHP also has an operator `selectMany`. 

  Alias for flatMap 

     RxPHP also has an operator `flatMapLatest`. 

  Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. Transform the items emitted by an Observable into Observables, and mirror those items emitted by the most-recently transformed Observable. The flatMapLatest operator is similar to the flatMap and concatMap methods described above, however, rather than emitting all of the items emitted by all of the Observables that the operator generates by transforming items from the source Observable, flatMapLatest instead emits items from each such transformed Observable only until the next such Observable is emitted, then it ignores the previous one and begins emitting items emitted by the new one. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/flatMap/flatMapLatest.php

$source = \Rx\Observable::range(1, 3)
    ->flatMapLatest(function ($x) {
        return \Rx\Observable::fromArray([$x . 'a', $x . 'b']);
    });

$source->subscribe($stdoutObserver);
```
  
```
Next value: 1a
Next value: 2a
Next value: 3a
Next value: 3b
Complete!
```
      RxPHP also has an operator `concatMap`. 

  Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/concat/concatMap.php

$source = Rx\Observable::range(0, 5)
    ->concatMap(function ($x, $i) {
        return \Rx\Observable::interval(100)
            ->take($x)
            ->map(function () use ($i) {
                return $i;
            });
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Next value: 2
Next value: 3
Next value: 3
Next value: 3
Next value: 4
Next value: 4
Next value: 4
Next value: 4
Complete!
```
      RxPHP also has an operator `concatMapTo`. 

  Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/concat/concatMapTo.php

$obs = \Rx\Observable::interval(100)
    ->take(3)
    ->mapWithIndex(function ($i) {
        return $i;
    });

$source = Rx\Observable::range(0, 5)
    ->concatMapTo($obs);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Next value: 5
Next value: 6
Next value: 7
Next value: 8
Next value: 9
Next value: 10
Next value: 11
Next value: 12
Next value: 13
Next value: 14
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/flatmap.html>

First
=====

 
> emit only the first item (or the first item that meets some condition) emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#first)  If you are only interested in the first item emitted by an Observable, or the first item that meets some criteria, you can filter the Observable with the First operator. 


 In some implementations, `First` is not implemented as a filtering operator that returns an Observable, but as a blocking function that returns a particular item at such time as the source Observable emits that item. In those implementations, if you instead want a filtering operator, you may have better luck with [`Take(1)`](take) or [`ElementAt(0)`](elementat). 


 In some implementations there is also a Single operator. It behaves similarly to First except that it waits until the source Observable terminates in order to guarantee that it only emits a single item (otherwise, rather than emitting that item, it terminates with an error). You can use this to not only take the first item from the source Observable but to also guarantee that there was only one item. 

  #### See Also

 * [ElementAt](elementat)
* [Last](last)
* [Take](take)
* [Introduction to Rx: First](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#First)
* [Introduction to Rx: Single](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Single)
* [Loading data from multiple sources with RxJava](http://blog.danlew.net/2015/06/22/loading-data-from-multiple-sources-with-rxjava/) by Dan Lew (example using Concat and First)
* [RxMarbles: `find`](http://rxmarbles.com/#find)
* [RxMarbles: `findIndex`](http://rxmarbles.com/#findIndex)
* [RxMarbles: `first`](http://rxmarbles.com/#first)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `first firstOrDefault latest mostRecent next single singleOrDefault takeFirst`

     In RxGroovy, this filtering operator is implemented as `first`, `firstOrDefault`, and `takeFirst`. 


 Somewhat confusingly, there are also `BlockingObservable` operators called `first` and `firstOrDefault` that block and then return items, rather than immediately returning Observables. 


 There are also several other operators that perform similar functions. 

 ### The Filtering Operators

  ![first](http://reactivex.io/documentation/operators/images/first.png)  To filter an Observable so that only its first emission is emitted, use the `first` operator with no parameters. 

 * Javadoc: [`first()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#first())
   ![first](http://reactivex.io/documentation/operators/images/firstN.png)  You can also pass a predicate function to `first`, in which case it will produce an Observable that emits only the first item from the source Observable that the predicate evaluates as `true`. 

 * Javadoc: [`first(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#first(rx.functions.Func1))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/firstOrDefault.png)  The `firstOrDefault` operator is similar to `first`, but you pass it a default item that it can emit if the source Observable fails to emit any items 

 * Javadoc: [`firstOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#firstOrDefault(T))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/firstOrDefaultN.png)  `firstOrDefault` also has a variant to which you can pass a predicate function, so that its Observable will emit the first item from the source Observable that the predicate evaluates as `true`, or the default item if no items emitted by the source Observable pass the predicate. 

 * Javadoc: [`firstOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#firstOrDefault(T))
   ![takeFirst](http://reactivex.io/documentation/operators/images/first.takefirst.png)  The `takeFirst` operator behaves similarly to `first`, with the exception of how these operators behave wihen the source Observable emits no items that satisfy the predicate. In such a case, `first` will throw a `NoSuchElementException` while `takeFirst` will return an empty Observable (one that calls `onCompleted` but never calls `onNext`). 

 * Javadoc: [`takeFirst(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeFirst(rx.functions.Func1))
   ![single](http://reactivex.io/documentation/operators/images/single.png)  The `single` operator is similar to `first`, but throws a `NoSuchElementException` if the source Observable does not emit exactly one item before successfully completing. 

 * Javadoc: [`single()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#single())
   ![single](http://reactivex.io/documentation/operators/images/single.p.png)  `single` also has a version that accepts a predicate, and emits the sole item emitted by the source Observable that matches that predicate, or notifies of an exception if exactly one such item does not match. 

 * Javadoc: [`single(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#single(rx.functions.Func1))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/singleOrDefault.png)  As with `firstOrDefault` there is also a `singleOrDefault` that emits a default item if the source Observable is empty, although it will still notify of an error if the source Observable emits more than one item. 

 * Javadoc: [`singleOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#singleOrDefault(T))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/singleOrDefault.p.png)  And there is also a verion of `singleOrDefault` that takes a predicate function and emits the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and makes an error notification if multiple items match. 

 * Javadoc: [`singleOrDefault(Func1,T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#singleOrDefault(rx.functions.Func1,%20T))
   `first`, `firstOrDefault`, `single`, `singleOrDefault`, and `takeFirst` do not by default operate on any particular [Scheduler](../scheduler). 

 ### The `BlockingObservable` Methods

  The `BlockingObservable` methods do not transform an Observable into another, filtered Observable, but rather they break out of the Observable cascade, blocking until the Observable emits the desired item, and then return that item itself. 


 To turn an Observable into a `BlockingObservable` so that you can use these methods, you can use either the `Observable.toBlocking` or `BlockingObservable.from` methods. 

 * Javadoc: [`Observable.toBlocking()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toBlocking())
* Javadoc: [`BlockingObservable.from(Observable)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#from(rx.Observable))

  ![first](http://reactivex.io/documentation/operators/images/B.first.png)  To retrieve the first emission from a `BlockingObservable`, use the `first` method with no parameters. 

 * Javadoc: [`BlockingObservable.first()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#first())
   ![first](http://reactivex.io/documentation/operators/images/B.first.p.png)  You can also pass a predicate function to the `first` method to retrieve the first emission from a `BlockingObservable` that satisfies the predicate. 

 * Javadoc: [`BlockingObservable.first(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#first(rx.functions.Func1))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/B.firstOrDefault.png)  As with the filtering operators, the `first` method of `BlockingObservable` will throw a `NoSuchElementException` if there is no first element in the source `BlockingObservable`. To return a default item instead in such cases, use the `firstOrDefault` method. 

 * Javadoc: [`BlockingObservable.firstOrDefault()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#firstOrDefault(T))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/B.firstOrDefault.p.png)  And, as with `first`, there is a `firstOrDefault` variant that takes a predicate function as an argument and returns the first item from the source `BlockingObservable` that satisfies that predicate, or a default item instead if no satisfying item was emitted. 

 * Javadoc: [`BlockingObservable.firstOrDefault(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#firstOrDefault(T,%20rx.functions.Func1))
   ![single](http://reactivex.io/documentation/operators/images/B.single.png)  The `single` operator is similar to `first`, but throws a `NoSuchElementException` if the source Observable does not emit exactly one item before successfully completing. 

 * Javadoc: [`single()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#single())
   ![single](http://reactivex.io/documentation/operators/images/B.single.p.png)  `single` also has a version that accepts a predicate, and returns the sole item emitted by the source Observable that matches that predicate, or throws an exception if exactly one such item does not match. 

 * Javadoc: [`single(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#single(rx.functions.Func1))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/B.singleOrDefault.png)  As with `firstOrDefault` there is also a `singleOrDefault` that returns a default item if the source Observable is empty, although it will still throw an error if the source Observable emits more than one item. 

 * Javadoc: [`singleOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#singleOrDefault(T))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/B.singleOrDefault.p.png)  And there is also a verion of `singleOrDefault` that takes a predicate function and returns the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and throws an error if multiple items match. 

 * Javadoc: [`singleOrDefault(Func1,T)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#singleOrDefault(rx.functions.Func1,%20T))
   ![next](http://reactivex.io/documentation/operators/images/B.next.png)  The `next` operator blocks until the `BlockingObservable` emits another item, and then returns that item. You can call this function repeatedly to get successive items from the `BlockingObservable`, effectively iterating over its emissions in a blocking fashion. 


 The `latest` operator is similar, but rather than blocking to wait for the next emitted item, it immediately returns the most-recently-emitted item, and only blocks if the Observable has not yet emitted anything. 

 * Javadoc: [`next()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#next())
* Javadoc: [`latest()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#latest())
   ![mostRecent](http://reactivex.io/documentation/operators/images/B.mostRecent.png)  The `mostRecent` operator similarly allows you to iterate over the emissions of a `BlockingObservable`, but its Iterable always immediately returns a value: either a default item you provide (if the `BlockingObservable` has not yet emitted an item), or the latest item the `BlockingObservable` has emitted. 

 * Javadoc: [`mostRecent(T)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#mostRecent(T))
       ###  RxJava 1․x `first firstOrDefault latest mostRecent next single singleOrDefault takeFirst`

     In RxJava, this filtering operator is implemented as `first`, `firstOrDefault`, and `takeFirst`. 


 Somewhat confusingly, there are also `BlockingObservable` operators called `first` and `firstOrDefault` that block and then return items, rather than immediately returning Observables. 


 There are also several other operators that perform similar functions. 

 ### The Filtering Operators

  ![first](http://reactivex.io/documentation/operators/images/first.png)  To filter an Observable so that only its first emission is emitted, use the `first` operator with no parameters. 

 #### Sample Code

 
```
Observable.just(1, 2, 3)
          .first()
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Sequence complete.
```
 * Javadoc: [`first()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#first())
   ![first](http://reactivex.io/documentation/operators/images/firstN.png)  You can also pass a predicate function to `first`, in which case it will produce an Observable that emits only the first item from the source Observable that the predicate evaluates as `true`. 

 * Javadoc: [`first(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#first(rx.functions.Func1))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/firstOrDefault.png)  The `firstOrDefault` operator is similar to `first`, but you pass it a default item that it can emit if the source Observable fails to emit any items 

 * Javadoc: [`firstOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#firstOrDefault(T))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/firstOrDefaultN.png)  `firstOrDefault` also has a variant to which you can pass a predicate function, so that its Observable will emit the first item from the source Observable that the predicate evaluates as `true`, or the default item if no items emitted by the source Observable pass the predicate. 

 * Javadoc: [`firstOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#firstOrDefault(T))
   ![takeFirst](http://reactivex.io/documentation/operators/images/first.takefirst.png)  The `takeFirst` operator behaves similarly to `first`, with the exception of how these operators behave wihen the source Observable emits no items that satisfy the predicate. In such a case, `first` will throw a `NoSuchElementException` while `takeFirst` will return an empty Observable (one that calls `onCompleted` but never calls `onNext`). 

 * Javadoc: [`takeFirst(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeFirst(rx.functions.Func1))
   ![single](http://reactivex.io/documentation/operators/images/single.png)  The `single` operator is similar to `first`, but throws a `NoSuchElementException` if the source Observable does not emit exactly one item before successfully completing. 

 * Javadoc: [`single()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#single())
   ![single](http://reactivex.io/documentation/operators/images/single.p.png)  `single` also has a version that accepts a predicate, and emits the sole item emitted by the source Observable that matches that predicate, or notifies of an exception if exactly one such item does not match. 

 * Javadoc: [`single(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#single(rx.functions.Func1))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/singleOrDefault.png)  As with `firstOrDefault` there is also a `singleOrDefault` that emits a default item if the source Observable is empty, although it will still notify of an error if the source Observable emits more than one item. 

 * Javadoc: [`singleOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#singleOrDefault(T))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/singleOrDefault.p.png)  And there is also a verion of `singleOrDefault` that takes a predicate function and emits the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and makes an error notification if multiple items match. 

 * Javadoc: [`singleOrDefault(Func1,T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#singleOrDefault(rx.functions.Func1,%20T))
   `first`, `firstOrDefault`, `single`, `singleOrDefault`, and `takeFirst` do not by default operate on any particular [Scheduler](../scheduler). 

 ### The `BlockingObservable` Methods

  The `BlockingObservable` methods do not transform an Observable into another, filtered Observable, but rather they break out of the Observable cascade, blocking until the Observable emits the desired item, and then return that item itself. 


 To turn an Observable into a `BlockingObservable` so that you can use these methods, you can use either the `Observable.toBlocking` or `BlockingObservable.from` methods. 

 * Javadoc: [`Observable.toBlocking()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toBlocking())
* Javadoc: [`BlockingObservable.from(Observable)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#from(rx.Observable))

  ![first](http://reactivex.io/documentation/operators/images/B.first.png)  To retrieve the first emission from a `BlockingObservable`, use the `first` method with no parameters. 

 * Javadoc: [`BlockingObservable.first()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#first())
   ![first](http://reactivex.io/documentation/operators/images/B.first.p.png)  You can also pass a predicate function to the `first` method to retrieve the first emission from a `BlockingObservable` that satisfies the predicate. 

 * Javadoc: [`BlockingObservable.first(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#first(rx.functions.Func1))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/B.firstOrDefault.png)  As with the filtering operators, the `first` method of `BlockingObservable` will throw a `NoSuchElementException` if there is no first element in the source `BlockingObservable`. To return a default item instead in such cases, use the `firstOrDefault` method. 

 * Javadoc: [`BlockingObservable.firstOrDefault()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#firstOrDefault(T))
   ![firstOrDefault](http://reactivex.io/documentation/operators/images/B.firstOrDefault.p.png)  And, as with `first`, there is a `firstOrDefault` variant that takes a predicate function as an argument and retrieves the first item from the source `BlockingObservable` that satisfies that predicate, or a default item instead if no satisfying item was emitted. 

 * Javadoc: [`BlockingObservable.firstOrDefault(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#firstOrDefault(T,%20rx.functions.Func1))
   ![single](http://reactivex.io/documentation/operators/images/B.single.png)  The `single` operator is similar to `first`, but throws a `NoSuchElementException` if the source Observable does not emit exactly one item before successfully completing. 

 * Javadoc: [`single()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#single())
   ![single](http://reactivex.io/documentation/operators/images/B.single.p.png)  `single` also has a version that accepts a predicate, and returns the sole item emitted by the source Observable that matches that predicate, or throws an exception if exactly one such item does not match. 

 * Javadoc: [`single(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#single(rx.functions.Func1))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/B.singleOrDefault.png)  As with `firstOrDefault` there is also a `singleOrDefault` that returns a default item if the source Observable is empty, although it will still throw an error if the source Observable emits more than one item. 

 * Javadoc: [`singleOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#singleOrDefault(T))
   ![singleOrDefault](http://reactivex.io/documentation/operators/images/B.singleOrDefault.p.png)  And there is also a verion of `singleOrDefault` that takes a predicate function and returns the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and throws an error if multiple items match. 

 * Javadoc: [`singleOrDefault(Func1,T)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#singleOrDefault(rx.functions.Func1,%20T))
   ![next](http://reactivex.io/documentation/operators/images/B.next.png)  The `next` operator blocks until the `BlockingObservable` emits another item, and then returns that item. You can call this function repeatedly to get successive items from the `BlockingObservable`, effectively iterating over its emissions in a blocking fashion. 


 The `latest` operator is similar, but rather than blocking to wait for the next emitted item, it immediately returns the most-recently-emitted item, and only blocks if the Observable has not yet emitted anything. 

 * Javadoc: [`next()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#next())
* Javadoc: [`latest()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#latest())
   ![mostRecent](http://reactivex.io/documentation/operators/images/B.mostRecent.png)  The `mostRecent` operator similarly allows you to iterate over the emissions of a `BlockingObservable`, but its Iterable always immediately returns a value: either a default item you provide (if the `BlockingObservable` has not yet emitted an item), or the latest item the `BlockingObservable` has emitted. 

 * Javadoc: [`mostRecent(T)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#mostRecent(T))
       ###  RxJS `find findIndex first single`

     ![first](http://reactivex.io/documentation/operators/images/firstN.png)  RxJS implements the `first` operator. It optionally takes a predicate function as a parameter, in which case, rather than emitting the first item from the source Observable, the resulting Observable will emit the first item from the source Observable that satisfies the predicate. 


 The predicate function itself takes three arguments: 

 1. the item from the source Observable to be, or not be, filtered
2. the zero-based index of this item in the source Observable’s sequence
3. the source Observable object

  An optional third parameter (named `defaultValue`) allows you to choose an item that `first` will emit if the source Observable does not emit any items (or if it does not emit the *n*th item that it expected. 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 10)
    .first(function (x, idx, obs) { return x % 2 === 1; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 1
Completed
```
  If the source Observable emits no items (or no items that match the predicate), `first` will terminate with a “`Sequence contains no elements.`” `onError` notification. 

    ![single](http://reactivex.io/documentation/operators/images/single.p.png)  The `single` operator is similar, except that it only emits its item once the source Observable successfully completes after emitting one item (or one item that matches the predicate). If it emits either no such items or more than one such item, `single` will terminate with an `onError` notitifcation (“`Sequence contains no elements.`”). 

    ![find](http://reactivex.io/documentation/operators/images/find.png)  The `find` operator is much like `first` except that the predicate argument is mandatory, and it behaves differently if no item from the source Observable matches the predicate. While `first` will send an `onError` notification in such a case, `find` will instead emit an `undefined` item. 

 #### Sample Code

 
```
var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .find(function (x, i, obs) {
        return x === 5;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: undefined
Completed
```
    ![findIndex](http://reactivex.io/documentation/operators/images/findIndex.png) 
 The `findIndex` operator is similar to `find`, except that instead of emitting the item that matches the predicate (or `undefined`), it emits the zero-based index of that item in the source Observable’s sequence (or `-1`). 

 #### Sample Code

 
```
var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .findIndex(function (x, i, obs) {
        return x === 5;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: -1
Completed
```
    `find`, `findIndex`, and `first` are found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  They each require one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/first.html>

Last
====

 
> emit only the last item (or the last item that meets some condition) emitted by an Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#last)  If you are only interested in the last item emitted by an Observable, or the last item that meets some criteria, you can filter the Observable with the Last operator. 


 In some implementations, `Last` is not implemented as a filtering operator that returns an Observable, but as a blocking function that returns a particular item when the source Observable terminates. In those implementations, if you instead want a filtering operator, you may have better luck with [`TakeLast(1)`](take). 

  #### See Also

 * [ElementAt](elementat)
* [First](first)
* [Take](take)
* [TakeLast](takelast)
* [Introduction to Rx: Last](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Last)
* [RxMarbles: `last`](http://rxmarbles.com/#last)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `last lastOrDefault`

     In RxGroovy, this filtering operator is implemented as `last` and `lastOrDefault`. 


 Somewhat confusingly, there are also `BlockingObservable` operators called `last` and `lastOrDefault` that block and then return items, rather than immediately returning Observables. 

 ### The Filtering Operators

  ![last](http://reactivex.io/documentation/operators/images/last.png)  To filter an Observable so that only its last emission is emitted, use the `last` operator with no parameters. 

 * Javadoc: [`last()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#last())
   ![last](http://reactivex.io/documentation/operators/images/last.p.png)  You can also pass a predicate function to `last`, in which case it will produce an Observable that emits only the last item from the source Observable that the predicate evaluates as `true`. 

 * Javadoc: [`last(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#last(rx.functions.Func1))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/lastOrDefault.png)  The `lastOrDefault` operator is similar to `last`, but you pass it a default item that it can emit if the source Observable fails to emit any items. 

 * Javadoc: [`lastOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#lastOrDefault(T))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/lastOrDefault.p.png)  `lastOrDefault` also has a variant to which you can pass a predicate function, so that its Observable will emit the last item from the source Observable that the predicate evaluates as `true`, or the default item if no items emitted by the source Observable pass the predicate. 

 * Javadoc: [`lastOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#lastOrDefault(T))
   `last` and `lastOrDefault` do not by default operate on any particular [Scheduler](../scheduler). 

 ### The `BlockingObservable` Methods

  The `BlockingObservable` methods do not transform an Observable into another, filtered Observable, but rather they break out of the Observable cascade, blocking until the Observable emits the desired item, and then return that item itself. 


 To turn an Observable into a `BlockingObservable` so that you can use these methods, you can use either the `Observable.toBlocking` or `BlockingObservable.from` methods. 

 * Javadoc: [`Observable.toBlocking()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toBlocking())
* Javadoc: [`BlockingObservable.from(Observable)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#from(rx.Observable))

  ![last](http://reactivex.io/documentation/operators/images/B.last.png)  To retrieve the last emission from a `BlockingObservable`, use the `last` method with no parameters. 

 * Javadoc: [`BlockingObservable.last()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#last())
   ![last](http://reactivex.io/documentation/operators/images/B.last.p.png)  You can also pass a predicate function to the `last` method to retrieve the last emission from a `BlockingObservable` that satisfies the predicate. 

 * Javadoc: [`BlockingObservable.last(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#last(rx.functions.Func1))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/B.lastOrDefault.png)  As with the filtering operators, the `last` method of `BlockingObservable` will throw a `NoSuchElementException` if there is no last element in the source `BlockingObservable`. To return a default item instead in such cases, use the `lastOrDefault` method. 

 * Javadoc: [`BlockingObservable.lastOrDefault()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#lastOrDefault(T))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/B.lastOrDefault.p.png)  And, as with `last`, there is a `lastOrDefault` variant that takes a predicate function as an argument and retrieves the last item from the source `BlockingObservable` that satisfies that predicate, or a default item instead if no satisfying item was emitted. 

 * Javadoc: [`BlockingObservable.lastOrDefault(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#lastOrDefault(T,%20rx.functions.Func1))
       ###  RxJava 1․x `last lastOrDefault`

     In RxJava, this filtering operator is implemented as `last` and `lastOrDefault`. 


 Somewhat confusingly, there are also `BlockingObservable` operators called `last` and `lastOrDefault` that block and then return items, rather than immediately returning Observables. 

 ### The Filtering Operators

  ![last](http://reactivex.io/documentation/operators/images/last.png)  To filter an Observable so that only its last emission is emitted, use the `last` operator with no parameters. 

 #### Sample Code

 
```
Observable.just(1, 2, 3)
          .last()
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 3
Sequence complete.
```
 * Javadoc: [`last()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#last())
   ![last](http://reactivex.io/documentation/operators/images/last.p.png)  You can also pass a predicate function to `last`, in which case it will produce an Observable that emits only the last item from the source Observable that the predicate evaluates as `true`. 

 * Javadoc: [`last(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#last(rx.functions.Func1))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/lastOrDefault.png)  The `lastOrDefault` operator is similar to `last`, but you pass it a default item that it can emit if the source Observable fails to emit any items. 

 * Javadoc: [`lastOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#lastOrDefault(T))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/lastOrDefault.p.png)  `lastOrDefault` also has a variant to which you can pass a predicate function, so that its Observable will emit the last item from the source Observable that the predicate evaluates as `true`, or the default item if no items emitted by the source Observable pass the predicate. 

 * Javadoc: [`lastOrDefault(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#lastOrDefault(T))
   `last` and `lastOrDefault` do not by default operate on any particular [Scheduler](../scheduler). 

 ### The `BlockingObservable` Methods

  The `BlockingObservable` methods do not transform an Observable into another, filtered Observable, but rather they break out of the Observable cascade, blocking until the Observable emits the desired item, and then return that item itself. 


 To turn an Observable into a `BlockingObservable` so that you can use these methods, you can use either the `Observable.toBlocking` or `BlockingObservable.from` methods. 

 * Javadoc: [`Observable.toBlocking()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toBlocking())
* Javadoc: [`BlockingObservable.from(Observable)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#from(rx.Observable))

  ![last](http://reactivex.io/documentation/operators/images/B.last.png)  To retrieve the last emission from a `BlockingObservable`, use the `last` method with no parameters. 

 * Javadoc: [`BlockingObservable.last()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#last())
   ![last](http://reactivex.io/documentation/operators/images/B.last.p.png)  You can also pass a predicate function to the `last` method to retrieve the last emission from a `BlockingObservable` that satisfies the predicate. 

 * Javadoc: [`BlockingObservable.last(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#last(rx.functions.Func1))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/B.lastOrDefault.png)  As with the filtering operators, the `last` method of `BlockingObservable` will throw a `NoSuchElementException` if there is no last element in the source `BlockingObservable`. To return a default item instead in such cases, use the `lastOrDefault` method. 

 * Javadoc: [`BlockingObservable.lastOrDefault()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#lastOrDefault(T))
   ![lastOrDefault](http://reactivex.io/documentation/operators/images/B.lastOrDefault.p.png)  And, as with `last`, there is a `lastOrDefault` variant that takes a predicate function as an argument and retrieves the last item from the source `BlockingObservable` that satisfies that predicate, or a default item instead if no satisfying item was emitted. 

 * Javadoc: [`BlockingObservable.lastOrDefault(Func1)`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#lastOrDefault(T,%20rx.functions.Func1))
       ###  RxJS `last`

     ![last](http://reactivex.io/documentation/operators/images/last.p.png)  RxJS implements the `last` operator. It optionally takes a predicate function as a parameter, in which case, rather than emitting the last item from the source Observable, the resulting Observable will emit the last item from the source Observable that satisfies the predicate. 


 The predicate function itself takes three arguments: 

 1. the item from the source Observable to be, or not be, filtered
2. the zero-based index of this item in the source Observable’s sequence
3. the source Observable object

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 10)
    .last(function (x, idx, obs) { return x % 2 === 1; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 8
Completed
```
  If the source Observable emits no items (or no items that match the predicate), `last` will terminate with a “`Sequence contains no elements.`” `onError` notification. 


 If instead you want the Observable to emit a default value in such a case, you can pass a second parameter (named `defaultValue`) to `last`: 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 10)
    .last(function (x, idx, obs) { return x > 42; }, 88 );

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 88
Completed
```
   `last` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/last.html>

StartWith
=========

 
> emit a specified sequence of items before beginning to emit the items from the source Observable

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#startWith)  If you want an Observable to emit a specific sequence of items before it begins emitting the items normally expected from it, apply the StartWith operator to it. 

   (If, on the other hand, you want to append a sequence of items to the end of those normally emitted by an Observable, you want the [Concat](concat) operator.) 

 #### See Also

 * [Concat](concat)
* [Introduction to Rx: StartWith](http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#StartWith)
* [RxMarbles: `startWith`](http://rxmarbles.com/#startWith)

 Language-Specific Information
-----------------------------

    ###  RxClojure `cons`

     ![cons](http://reactivex.io/documentation/operators/images/cons.png)  RxClojure implements this operator as `cons`. It takes an item and an Observable as parameters, and prepends the item to the items emitted by the Observable as its own Observable sequence. 

       ###  RxCpp `start_with`

     ![start_with](http://reactivex.io/documentation/operators/images/start_with.png)  RxCpp implements this operator as `start_with`. It takes an Observable and one or more items as parameters, and prepends these items, in the order they are given in the parameter list, to the items emitted by the Observable as its own Observable sequence. 

       ###  RxGroovy `startWith`

     RxGroovy implements this operator as `startWith`. 

  ![startWith](http://reactivex.io/documentation/operators/images/startWith.png)  You can pass the values you want to prepend to the Observable sequence to `startWith` either in a single Iterable or as a series of one to nine function parameters. 

 #### Sample Code

 
```
def myObservable = Observable.from([1, 2, 3]);

myObservable.startWith(-3, -2, -1, 0).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
-3
-2
-1
0
1
2
3
```
 * Javadoc: [`startWith(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#startWith(java.lang.Iterable))
* Javadoc: [`startWith(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#startWith(T)) (there are also versions that take up to nine individual items)
   ![startWith](http://reactivex.io/documentation/operators/images/startWith.o.png)  You can also pass `startWith` an Observable, and it will prepend the emissions from that Observable to those of the source Observable to make its own set of emissions. This is a sort of inverted Concat operation. 

 * Javadoc: [`startWith(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#startWith(rx.Observable))
       ###  RxJava 1․x `startWith`

     RxJava implements this operator as `startWith`. 

  ![startWith](http://reactivex.io/documentation/operators/images/startWith.png)  You can pass the values you want to prepend to the Observable sequence to `startWith` either in a single Iterable or as a series of one to nine function parameters. 

 * Javadoc: [`startWith(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#startWith(java.lang.Iterable))
* Javadoc: [`startWith(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#startWith(T)) (there are also versions that take up to nine individual items)
   ![startWith](http://reactivex.io/documentation/operators/images/startWith.o.png)  You can also pass `startWith` an Observable, and it will prepend the emissions from that Observable to those of the source Observable to make its own set of emissions. This is a sort of inverted Concat operation. 

 * Javadoc: [`startWith(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#startWith(rx.Observable))
       ###  RxJS `startWith`

     ![startWith](http://reactivex.io/documentation/operators/images/startWith.png)  RxJS implements this operator as `startWith`. It accepts a variable number of function parameters and treats each one as an item that it will prepend to the resulting Observable sequence in the order they are given in the parameter list. 

   `startWith` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxKotlin `startWith`

     RxKotlin implements this operator as `startWith`. 

  ![startWith](http://reactivex.io/documentation/operators/images/startWith.png)  You can pass the values you want to prepend to the Observable sequence to `startWith` either in a single Iterable or as a series of one to nine function parameters. 

   ![startWith](http://reactivex.io/documentation/operators/images/startWith.o.png)  You can also pass `startWith` an Observable, and it will prepend the emissions from that Observable to those of the source Observable to make its own set of emissions. This is a sort of inverted Concat operation. 

       ###  RxNet `StartWith`

     ![StartWith](http://reactivex.io/documentation/operators/images/startWith.C.png)  Rx.NET implements this operator as `StartWith`. It accepts an array of items which it prepends to the resulting Observable sequence in the order they appear in the array before it emits the items from the source Observable. 

       ###  RxPHP `startWith startWithArray`

       RxPHP implements this operator as `startWith`. 

  Prepends a value to an observable sequence with an argument of a signal value to prepend. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/startWith/startWith.php

$source = \Rx\Observable::of(2)
    ->startWith(1);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Complete!
```
      RxPHP also has an operator `startWithArray`. 

  Prepends a sequence of values to an observable sequence with an argument of an array of values to prepend. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/startWith/startWithArray.php

$source = \Rx\Observable::of(4)
    ->startWithArray([1, 2, 3]);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Complete!
```
         ###  RxPY `start_with`

     ![start_with](http://reactivex.io/documentation/operators/images/start_with.png)  RxPY implements this operator as `start_with`. It accepts an array of items which it prepends to the resulting Observable sequence in the order they appear in the array before it emits the items from the source Observable. 

       ###  Rxrb `start_with`

     ![start_with](http://reactivex.io/documentation/operators/images/start_with.png)  Rx.rb implements this operator as `start_with`. It accepts an array of items which it prepends to the resulting Observable sequence in the order they appear in the array before it emits the items from the source Observable. 

       ###  RxScala `+:`

     ![plus colon](http://reactivex.io/documentation/operators/images/pluscolon.png)  RxScala implements this operator with `+:` It takes an item and an Observable as parameters, and prepends the item to the items emitted by the Observable as its own Observable sequence. 

     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/startwith.html>

Switch
======

 
> convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables

  ![Switch](http://reactivex.io/documentation/operators/images/switch.c.png)  Switch subscribes to an Observable that emits Observables. Each time it observes one of these emitted Observables, the Observable returned by Switch unsubscribes from the previously-emitted Observable begins emitting items from the latest Observable. Note that it will unsubscribe from the previously-emitted Observable when a new Observable is emitted from the source Observable, not when the new Observable emits an item. This means that items emitted by the previous Observable between the time the subsequent Observable is emitted and the time that subsequent Observable itself begins emitting items will be dropped (as with the yellow circle in the diagram above). 

  #### See Also

 * [Amb](amb)
* [Concat](concat)
* [FlatMap](flatmap)
* [Introduction to Rx: Switch](http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#Switch)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `switchOnNext`

     ![switch](http://reactivex.io/documentation/operators/images/switchDo.png)  RxGroovy implements this operator as `switchOnNext`. It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`switchOnNext(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#switchOnNext(rx.Observable))
       ###  RxJava 1․x `switchOnNext`

     ![switch](http://reactivex.io/documentation/operators/images/switchDo.png)  RxJava implements this operator as `switchOnNext`. It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`switchOnNext(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#switchOnNext(rx.Observable))
       ###  RxJS `switch`

     ![switch](http://reactivex.io/documentation/operators/images/switch.png)  RxJS implements this operator as `switch` 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 3)
    .select(function (x) { return Rx.Observable.range(x, 3); })
    .switch();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed
```
 `switch` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`
       ###  RxPHP `switch switchFirst`

       RxPHP implements this operator as `switch`. 

  Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/switch/switch.php

$source = Rx\Observable::range(0, 3)
    ->map(function ($x) {
        return \Rx\Observable::range($x, 3);
    })
    ->switch();

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Complete!
```
      RxPHP also has an operator `switchFirst`. 

  Receives an Observable of Observables and propagates the first Observable exclusively until it completes before it begins subscribes to the next Observable. Observables that come before the current Observable completes will be dropped and will not propagate. This operator is similar to concatAll() except that it will not hold onto Observables that come in before the current one is finished completed. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/switch/switchFirst.php

$source = Rx\Observable::fromArray([
    \Rx\Observable::interval(100)->mapTo('a'),
    \Rx\Observable::interval(200)->mapTo('b'),
    \Rx\Observable::interval(300)->mapTo('c'),
])
    ->switchFirst()
    ->take(3);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: a
Next value: a
Next value: a
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/switch.html>

Materialize/Dematerialize
=========================

 
> represent both the items emitted and the notifications sent as emitted items, or reverse this process

  ![Materialize](http://reactivex.io/documentation/operators/images/materialize.c.png)  A well-formed, finite Observable will invoke its observer’s `onNext` method zero or more times, and then will invoke either the `onCompleted` or `onError` method exactly once. The Materialize operator converts this series of invocations — both the original `onNext` notifications and the terminal `onCompleted` or `onError` notification — into a series of *items* emitted by an Observable. 

   ![Dematerialize](http://reactivex.io/documentation/operators/images/dematerialize.c.png)  The Dematerialize operator reverses this process. It operates on an Observable that has previously been transformed by Materialize and returns it to its original form. 

  #### See Also

 * [Introduction to Rx: Materialize and Dematerialize](http://www.introtorx.com/Content/v1.0.10621.0/08_Transformation.html#MaterializeAndDematerialize)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `dematerialize materialize`

     ![materialize](http://reactivex.io/documentation/operators/images/materialize.png)  In RxGroovy, `materialize` transforms the notifications from the source Observable into `Notification` objects and emits them as the emissions from the Observable it returns. For example: 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3]);

numbers.materialize().subscribe(
  { if(rx.Notification.Kind.OnNext == it.kind) { println("Next: " + it.value); }
    else if(rx.Notification.Kind.OnCompleted == it.kind) { println("Completed"); }
    else if(rx.Notification.Kind.OnError == it.kind) { println("Error: " + it.exception); } },
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
Next: 1
Next: 2
Next: 3
Completed
Sequence complete
```
  `materialize` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`materialize()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#materialize())
   ![dematerialize](http://reactivex.io/documentation/operators/images/dematerialize.png)  `dematerialize` reverses this process: converting the emitted `Notification` objects from the source Observable into notifications from the resulting Observable. The following example dematerializes the materialized Observable from the previous section: 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3]);

numbers.materialize().dematerialize().subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
2
3
Sequence complete
```
  `dematerialize` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`dematerialize()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#dematerialize())
       ###  RxJava 1․x `dematerialize materialize`

     ![materialize](http://reactivex.io/documentation/operators/images/materialize.png)  In RxJava, `materialize` transforms the notifications from the source Observable into `Notification` objects and emits them as the emissions from the Observable it returns. 

  `materialize` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`materialize()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#materialize())
   ![dematerialize](http://reactivex.io/documentation/operators/images/dematerialize.png)  `dematerialize` reverses this process: converting the emitted `Notification` objects from the source Observable into notifications from the resulting Observable. 

  `dematerialize` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`dematerialize()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#dematerialize())
       ###  RxJS `dematerialize`

     ![dematerialize](http://reactivex.io/documentation/operators/images/dematerialize.png)  RxJS only implements the `dematerialize` operator. If you want a “materialized” Observable, you have to assemble it by hand by manually creating and emitting the `Notification` objects that represent Observable notification calls. 

 #### Sample Code

 
```
var source = Rx.Observable
    .fromArray([
        Rx.Notification.createOnNext(42),
        Rx.Notification.createOnError(new Error('woops'))
    ])
    .dematerialize();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x.toString()); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Error: Error: woops
```
  `dematerialize` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `materialize dematerialize`

       RxPHP implements this operator as `materialize`. 

  Materializes the implicit notifications of an observable sequence as explicit notifications. 

     RxPHP also has an operator `dematerialize`. 

  Dematerializes the explicit notification values of an observable sequence as implicit notifications. 

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/materialize-dematerialize.html>

ObserveOn
=========

 
> specify the Scheduler on which an observer will observe this Observable

  ![ObserveOn](http://reactivex.io/documentation/operators/images/observeOn.c.png)  Many implementations of ReactiveX use [“`Scheduler`s”](../scheduler) to govern an Observable’s transitions between threads in a multi-threaded environment. You can instruct an Observable to send its notifications to observers on a particular Scheduler by means of the ObserveOn operator. 

   ![ObserveOn](http://reactivex.io/documentation/operators/images/observeOn.e.png)  Note that ObserveOn will forward an `onError` termination notification immediately if it receives one, and will not wait for a slow-consuming observer to receive any not-yet-emitted items that it is aware of first. This may mean that the `onError` notification jumps ahead of (and swallows) items emitted by the source Observable, as in the diagram above. 

   ![ObserveOn and SubscribeOn](http://reactivex.io/documentation/operators/images/schedulers.png)  The [SubscribeOn](subscribeon) operator is similar, but it instructs the Observable to *itself* operate on the specified Scheduler, as well as notifying its observers on that Scheduler. 


 By default, an Observable and the chain of operators that you apply to it will do its work, and will notify its observers, on the same thread on which its `Subscribe` method is called. The SubscribeOn operator changes this behavior by specifying a different Scheduler on which the Observable should operate. The ObserveOn operator specifies a different Scheduler that the Observable will use to send notifications to its observers. 


 As shown in this illustration, the SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called. ObserveOn, on the other hand, affects the thread that the Observable will use *below* where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate. 

  #### See Also

 * [`Scheduler`](../scheduler)
* [SubscribeOn](subscribeon)
* [Rx Workshop: Schedulers](http://channel9.msdn.com/Series/Rx-Workshop/Rx-Workshop-Schedulers)
* [RxJava Threading Examples by Graham Lea](http://www.grahamlea.com/2014/07/rxjava-threading-examples/)
* [Introduction to Rx: SubscribeOn and ObserveOn](http://www.introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html#SubscribeOnObserveOn)
* [RxJava: Understanding observeOn() and subscribeOn()](http://tomstechnicalblog.blogspot.hu/2016/02/rxjava-understanding-observeon-and.html) by Thomas Nield
* [Advanced Reactive Java: SubscribeOn and ObserveOn](http://akarnokd.blogspot.hu/2016/03/subscribeon-and-observeon.html) by Dávid Karnok

 Language-Specific Information
-----------------------------

    ###  RxGroovy `observeOn`

     ![observeOn](http://reactivex.io/documentation/operators/images/observeOn.png)  To specify on which Scheduler the Observable should invoke its observers’ `onNext`, `onCompleted`, and `onError` methods, use the `observeOn` operator, passing it the appropriate `Scheduler`. 

 * Javadoc: [`observeOn(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#observeOn(rx.Scheduler))
       ###  RxJava 1․x `observeOn`

     ![observeOn](http://reactivex.io/documentation/operators/images/observeOn.png)  To specify on which Scheduler the Observable should invoke its observers’ `onNext`, `onCompleted`, and `onError` methods, use the `observeOn` operator, passing it the appropriate `Scheduler`. 

 * Javadoc: [`observeOn(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#observeOn(rx.Scheduler))
       ###  RxJS `observeOn`

     ![observeOn](http://reactivex.io/documentation/operators/images/observeOn.png)  To specify on which Scheduler the Observable should invoke its observers’ `onNext`, `onCompleted`, and `onError` methods, use the `observeOn` operator, passing it the appropriate `Scheduler`. 

 #### Sample Code

 
```
/* Change from immediate scheduler to timeout */
var source = Rx.Observable.return(42, Rx.Scheduler.immediate)
    .observeOn(Rx.Scheduler.timeout);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Completed
```
  `observeOn` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/observeon.html>

Serialize
=========

 
> force an Observable to make serialized calls and to be well-behaved

  ![Serialize](http://reactivex.io/documentation/operators/images/serialize.c.png)  It is possible for an Observable to invoke its observers’ methods asynchronously, perhaps from different threads. This could make such an Observable violate [the Observable contract](../contract), in that it might try to send an `OnCompleted` or `OnError` notification before one of its `OnNext` notifications, or it might make an `OnNext` notification from two different threads concurrently. You can force such an Observable to be well-behaved and synchronous by applying the Serialize operator to it. 

  Language-Specific Information
-----------------------------

    ###  RxGroovy `serialize`

     ![serialize](http://reactivex.io/documentation/operators/images/synchronize.png)  RxGroovy implements this operator as `serialize`. It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`serialize()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#serialize())
       ###  RxJava 1․x `serialize`

     ![serialize](http://reactivex.io/documentation/operators/images/synchronize.png)  RxJava implements this operator as `serialize`. It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`serialize()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#serialize())
     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/serialize.html>

SubscribeOn
===========

 
> specify the Scheduler on which an Observable will operate

  ![SubscribeOn](http://reactivex.io/documentation/operators/images/subscribeOn.c.png)  Many implementations of ReactiveX use [“`Scheduler`s”](../scheduler) to govern an Observable’s transitions between threads in a multi-threaded environment. You can instruct an Observable to do its work on a particular Scheduler by calling the Observable’s SubscribeOn operator. 

   The [ObserveOn](observeon) operator is similar, but more limited. It instructs the Observable to send notifications to observers on a specified Scheduler. 


 In some implementations there is also an UnsubscribeOn operator. 

  ![ObserveOn and SubscribeOn](http://reactivex.io/documentation/operators/images/schedulers.png)  By default, an Observable and the chain of operators that you apply to it will do its work, and will notify its observers, on the same thread on which its `Subscribe` method is called. The SubscribeOn operator changes this behavior by specifying a different Scheduler on which the Observable should operate. The ObserveOn operator specifies a different Scheduler that the Observable will use to send notifications to its observers. 


 As shown in this illustration, the SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called. ObserveOn, on the other hand, affects the thread that the Observable will use *below* where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate. 

  #### See Also

 * [`Scheduler`](../scheduler)
* [ObserveOn](observeon)
* [Rx Workshop: Schedulers](http://channel9.msdn.com/Series/Rx-Workshop/Rx-Workshop-Schedulers)
* [RxJava Threading Examples](http://www.grahamlea.com/2014/07/rxjava-threading-examples/) by Graham Lea
* [Introduction to Rx: SubscribeOn and ObserveOn](http://www.introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html#SubscribeOnObserveOn)
* [Async Abstractions using rx-java](http://java.dzone.com/articles/async-abstractios-using-rx) by Biju Kunjummen, DZone
* [RxJava: Understanding observeOn() and subscribeOn()](http://tomstechnicalblog.blogspot.hu/2016/02/rxjava-understanding-observeon-and.html) by Thomas Nield
* [Advanced Reactive Java: SubscribeOn and ObserveOn](http://akarnokd.blogspot.hu/2016/03/subscribeon-and-observeon.html) by Dávid Karnok

 Language-Specific Information
-----------------------------

    ###  RxGroovy `subscribeOn unsubscribeOn`

     ![subscribeOn](http://reactivex.io/documentation/operators/images/subscribeOn.png)  To specify on which Scheduler the Observable should operate, use the `subscribeOn` operator, passing it the appropriate `Scheduler`. 

 * Javadoc: [`subscribeOn(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribeOn(rx.Scheduler))
   To specify which Scheduler observers will use to unsubscribe from an Observable, use the `unsubscribeOn` operator, passing it the appropriate `Scheduler`. 

 * Javadoc: [`unsubscribeOn(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#unsubscribeOn(rx.Scheduler))

      ###  RxJava 1․x `subscribeOn unsubscribeOn`

     ![subscribeOn](http://reactivex.io/documentation/operators/images/subscribeOn.png)  To specify on which Scheduler the Observable should operate, use the `subscribeOn` operator, passing it the appropriate `Scheduler`. 

 * Javadoc: [`subscribeOn(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#subscribeOn(rx.Scheduler))
   To specify which Scheduler observers will use to unsubscribe from an Observable, use the `unsubscribeOn` operator, passing it the appropriate `Scheduler`. 

 * Javadoc: [`unsubscribeOn(Scheduler)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#unsubscribeOn(rx.Scheduler))

      ###  RxJS `subscribeOn`

     ![subscribeOn](http://reactivex.io/documentation/operators/images/subscribeOn.png)  To specify on which Scheduler the Observable should operate, use the `subscribeOn` operator, passing it the appropriate `Scheduler`. 

 #### Sample Code

 
```
/* Change from immediate scheduler to timeout */
var source = Rx.Observable.return(42, Rx.Scheduler.immediate)
    .subscribeOn(Rx.Scheduler.timeout);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Completed
```
  `subscribeOn` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/subscribeon.html>

Using
=====

 
> create a disposable resource that has the same lifespan as the Observable

  ![Using](http://reactivex.io/documentation/operators/images/using.c.png)  The Using operator is a way you can instruct an Observable to create a resource that exists only during the lifespan of the Observable and is disposed of when the Observable terminates. 

  #### See Also

 * [Introduction to Rx: Using](http://www.introtorx.com/Content/v1.0.10621.0/11_AdvancedErrorHandling.html#Using)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `using`

     ![using](http://reactivex.io/documentation/operators/images/using.png)  You pass the `using` operator three parameters: 


1. a factory function that creates a disposable resource
2. a factory function that creates an Observable
3. a function that disposes of the resource


 When an observer subscribes to the Observable returned from `using`, `using` will use the Observable factory function to create the Observable the observer will observe, while at the same time using the resource factory function to create whichever resource you have designed it to make. When the observer unsubscribes from the Observable, or when the Observable terminates (normally or with an error), `using` will call the third function to dispose of the resource it created. 


 `using` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`using(Func0,Func1,Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#using(rx.functions.Func0,%20rx.functions.Func1,%20rx.functions.Action1))
       ###  RxJava 1․x `using`

     ![using](http://reactivex.io/documentation/operators/images/using.png)  You pass the `using` operator three parameters: 


1. a factory function that creates a disposable resource
2. a factory function that creates an Observable
3. a function that disposes of the resource


 When an observer subscribes to the Observable returned from `using`, `using` will use the Observable factory function to create the Observable the observer will observe, while at the same time using the resource factory function to create whichever resource you have designed it to make. When the observer unsubscribes from the Observable, or when the Observable terminates (normally or with an error), `using` will call the third function to dispose of the resource it created. 


 `using` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`using(Func0,Func1,Action1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#using(rx.functions.Func0,%20rx.functions.Func1,%20rx.functions.Action1))
       ###  RxJS `using`

     ![using](http://reactivex.io/documentation/operators/images/using.js.png)  You pass the `using` operator two parameters: 


1. a factory function that creates a disposable resource
2. a factory function that creates an Observable


 When an observer subscribes to the Observable returned from `using`, `using` will use the Observable factory function to create the Observable the observer will observe, while at the same time using the resource factory function to create whichever resource you have designed it to make. To dispose of the resource, call the `dispose` method of the subscription that was returned from the `subscribe` call you used to subscribe an observer to the Observable that you modified with `using`. 

 #### Sample Code

 
```
/* Using an AsyncSubject as a resource which supports the .dispose method */
function DisposableResource(value) {
  this.value = value;
  this.disposed = false;
}

DisposableResource.prototype.getValue = function () {
  if (this.disposed) {
    throw new Error('Object is disposed');
  }
  return this.value;
};

DisposableResource.prototype.dispose = function () {
  if (!this.disposed) {
    this.disposed = true;
    this.value = null;
  }
  console.log('Disposed');
};

var source = Rx.Observable.using(
  function () { return new DisposableResource(42); },
  function (resource) {
    var subject = new Rx.AsyncSubject();
    subject.onNext(resource.getValue());
    subject.onCompleted();
    return subject;
  }
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 42
Completed
```
 
```
subscription.dispose();
```
 
```
Disposed
```
  `using` is found in each of the following distributions: 

 * `rx.js`
* `rx.compat.js`
     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/using.html>

Merge
=====

 
> combine multiple Observables into one by merging their emissions

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#merge)  You can combine the output of multiple Observables so that they act like a single Observable, by using the Merge operator. 


 Merge may interleave the items emitted by the merged Observables (a similar operator, [Concat](concat), does not interleave items, but emits all of each source Observable’s items in turn before beginning to emit items from the next source Observable). 


 As shown in the above diagram, an `onError` notification from any of the source Observables will immediately be passed through to observers and will terminate the merged Observable. 

   ![MergeDelayError](http://reactivex.io/documentation/operators/images/mergeDelayError.C.png)  In many ReactiveX implementations there is a second operator, MergeDelayError, that changes this behavior — reserving `onError` notifications until all of the merged Observables complete and only then passing it along to the observers: 

  #### See Also

 * [Concat](concat)
* [Introduction to Rx: Merge](http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#Merge)
* [RxMarbles: `merge`](http://rxmarbles.com/#merge)
* [101 Rx Samples: Merge](http://rxwiki.wikidot.com/101samples#toc47)

 Language-Specific Information
-----------------------------

    ###  RxClojure `interleave interleave* merge merge* merge-delay-error merge-delay-error*`

     In RxClojure there are six operators of concern here: 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)  `merge` converts two or more Observables into a single Observable that emits all of the items emitted by all of those Observables. 

   ![merge*](http://reactivex.io/documentation/operators/images/mergeX.png)  `merge*` converts an Observable that emits Observables into a single Observable that emits all of the items emitted by all of the emitted Observables. 

   ![merge-delay-error](http://reactivex.io/documentation/operators/images/merge-delay-error.png)  `merge-delay-error` is like `merge`, but will emit all items from all of the merged Observables even if one or more of those Observables terminates with an `onError` notification while emissions are still pending. 


 `merge-delay-error*` is a similarly-modified version of `merge*`. 

   ![interleave*](http://reactivex.io/documentation/operators/images/interleaveX.png)  `interleave` is like `merge`, but more deliberate about how it interleaves the items from the source Observables: the resulting Observable emits the first item emitted by the first source Observable, then the first item emitted by the second source Observable, and so forth, and having reached the last source Observable, then emits the second item emitted by the first source Observable, the second item emitted by the second source Observable, and so forth, until all of the source Observables terminate. 


 `interleave*` is similar but operates on an Observable of Observables. 

       ###  RxCpp `merge`

     RxCpp implements this operator as `merge`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)       ###  RxGroovy `merge mergeDelayError mergeWith`

     RxGroovy implements this operator as `merge`, `mergeWith`, and `mergeDelayError`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)  For example, the following code merges the `odds` and `evens` into a single Observable. (The `subscribeOn` operator makes `odds` operate on a different thread from `evens` so that the two Observables may both emit items at the same time, to demonstrate how Merge may interleave these items.) 

 #### Sample Code

 
```
odds  = Observable.from([1, 3, 5, 7]).subscribeOn(someScheduler);
evens = Observable.from([2, 4, 6]);

Observable.merge(odds,evens).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
3
2
5
4
7
6
Sequence complete
```
  Instead of passing multiple Observables (up to nine) into `merge`, you could also pass in a `List<>` (or other Iterable) of Observables, an Array of Observables, or even an Observable that emits Observables, and `merge` will merge their output into the output of a single Observable: 

 * Javadoc: [`merge(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(java.lang.Iterable))
* Javadoc: [`merge(Iterable,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(java.lang.Iterable,%20int))
* Javadoc: [`merge(Observable[])`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable%5B%5D))
* Javadoc: [`merge(Observable[], int)` (RxGroovy 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable%5B%5D,%20int))
* Javadoc: [`merge(Observable, Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observables)
   ![merge(List)](http://reactivex.io/documentation/operators/images/merge.io.png)  If you pass in an Observable of Observables, you have the option of also passing in a value indicating to `merge` the maximum number of those Observables it should attempt to be subscribed to simultaneously. Once it reaches this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. 

 * Javadoc: [`merge(Observable<Observable>)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable))
* Javadoc: [`merge(Observable<Observable>,int)` (RxGroovy 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable,%20int))
   The instance version of `merge` is `mergeWith`, so, for example, in the code sample above, instead of writing `Observable.merge(odds,evens)` you could also write `odds.mergeWith(evens)`. 

 * Javadoc: [`mergeWith(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#mergeWith(rx.Observable))

  If any of the individual Observables passed into `merge` terminates with an `onError` notification, the Observable produced by `merge` itself will immediately terminate with an `onError` notification. If you would prefer a merge that continues emitting the results of the remaining, error-free Observables before reporting the error, use `mergeDelayError` instead. 

  ![mergeDelayError](http://reactivex.io/documentation/operators/images/mergeDelayError.png)  `mergeDelayError` behaves much like `merge`. The exception is when one of the Observables being merged terminates with an `onError` notification. If this happens with `merge`, the merged Observable will immediately issue an `onError` notification and terminate. `mergeDelayError`, on the other hand, will hold off on reporting the error until it has given any other non-error-producing Observables that it is merging a chance to finish emitting their items, and it will emit those itself, and will only terminate with an `onError` notification when all of the other merged Observables have finished. 


 Because it is possible that more than one of the merged Observables encountered an error, `mergeDelayError` may pass information about *multiple* errors in the `onError` notification (it will never invoke the observer’s `onError` method more than once). For this reason, if you want to know the nature of these errors, you should write your observers’ `onError` methods so that they accept a parameter of the class `CompositeException`. 


 `mergeDelayError` has fewer variants. You cannot pass it an Iterable or Array of Observables, but you can pass it an Observable that emits Observables or between one and nine individual Observables as parameters. There is not an instance method version of `mergeDelayError` as there is for `merge`. 

 * Javadoc: [`mergeDelayError(Observable<Observable>)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#mergeDelayError(rx.Observable))
* Javadoc: [`mergeDelayError(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#mergeDelayError(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observables)
       ###  RxJava 1․x `merge mergeDelayError mergeWith`

     RxJava implements this operator as `merge`, `mergeWith`, and `mergeDelayError`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png) #### Sample Code

 
```
Observable<Integer> odds = Observable.just(1, 3, 5).subscribeOn(someScheduler);
Observable<Integer> evens = Observable.just(2, 4, 6);

Observable.merge(odds, evens)
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
```
 
```
Next: 1
Next: 3
Next: 5
Next: 2
Next: 4
Next: 6
Sequence complete.
```
 * Javadoc: [`merge(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(java.lang.Iterable))
* Javadoc: [`merge(Iterable,int)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(java.lang.Iterable,%20int))
* Javadoc: [`merge(Observable[])`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable%5B%5D))
* Javadoc: [`merge(Observable[], int)` (RxJava 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable%5B%5D,%20int))
* Javadoc: [`merge(Observable, Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observables)
   Instead of passing multiple Observables (up to nine) into `merge`, you could also pass in a `List<>` (or other Iterable) of Observables, an Array of Observables, or even an Observable that emits Observables, and `merge` will merge their output into the output of a single Observable: 

  ![merge(List)](http://reactivex.io/documentation/operators/images/merge.io.png)  If you pass in an Observable of Observables, you have the option of also passing in a value indicating to `merge` the maximum number of those Observables it should attempt to be subscribed to simultaneously. Once it reaches this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. 

 * Javadoc: [`merge(Observable<Observable>)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable))
* Javadoc: [`merge(Observable<Observable>, int)` (RxJava 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#merge(rx.Observable,%20int))
   The instance version of `merge` is `mergeWith`, so, for example, instead of writing `Observable.merge(odds,evens)` you could also write `odds.mergeWith(evens)`. 


 If any of the individual Observables passed into `merge` terminates with an `onError` notification, the Observable produced by `merge` itself will immediately terminate with an `onError` notification. If you would prefer a merge that continues emitting the results of the remaining, error-free Observables before reporting the error, use `mergeDelayError` instead. 

  ![mergeDelayError](http://reactivex.io/documentation/operators/images/mergeDelayError.png)  `mergeDelayError` behaves much like `merge`. The exception is when one of the Observables being merged terminates with an `onError` notification. If this happens with `merge`, the merged Observable will immediately issue an `onError` notification and terminate. `mergeDelayError`, on the other hand, will hold off on reporting the error until it has given any other non-error-producing Observables that it is merging a chance to finish emitting their items, and it will emit those itself, and will only terminate with an `onError` notification when all of the other merged Observables have finished. 


 Because it is possible that more than one of the merged Observables encountered an error, `mergeDelayError` may pass information about *multiple* errors in the `onError` notification (it will never invoke the observer’s `onError` method more than once). For this reason, if you want to know the nature of these errors, you should write your observers’ `onError` methods so that they accept a parameter of the class `CompositeException`. 


 `mergeDelayError` has fewer variants. You cannot pass it an Iterable or Array of Observables, but you can pass it an Observable that emits Observables or between one and nine individual Observables as parameters. There is not an instance method version of `mergeDelayError` as there is for `merge`. 

 * Javadoc: [`mergeDelayError(Observable<Observable>)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#mergeDelayError(rx.Observable))
* Javadoc: [`mergeDelayError(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#mergeDelayError(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observables)
       ###  RxJS `merge mergeAll mergeDelayError`

     ![merge](http://reactivex.io/documentation/operators/images/merge.png)  The first variant of `merge` is an instance operator that takes a variable number of Observables as parameters, merging each of these Observables with the source (instance) Observables to produce its single output Observable. 

  This first variant of `merge` is found in the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

  The second variant of `merge` is a prototype (class) operator that accepts two parameters. The second of these is an Observable that emits the Observables you want to merge. The first is a number that indicates the maximum number of these emitted Observables that you want `merge` to attempt to be subscribed to at any moment. Once it reaches this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. 


 This second variant of `merge` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![mergeAll](http://reactivex.io/documentation/operators/images/mergeAll.png)  `mergeAll` is like this second variant of `merge` except that it does not allow you to set this maximum subscription count. It only takes the single parameter of an Observable of Observables. 

  `mergeAll` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![mergeDelayError](http://reactivex.io/documentation/operators/images/mergeDelayError.png)  If any of the individual Observables passed into `merge` or `mergeAll` terminates with an `onError` notification, the resulting Observable will immediately terminate with an `onError` notification. If you would prefer a merge that continues emitting the results of the remaining, error-free Observables before reporting the error, use `mergeDelayError` instead. 

 #### Sample Code

 
```
var source1 = Rx.Observable.of(1,2,3);
var source2 = Rx.Observable.throwError(new Error('whoops!'));
var source3 = Rx.Observable.of(4,5,6);

var merged = Rx.Observable.mergeDelayError(source1, source2, source3);

var subscription = merged.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); }
  function () { console.log('Completed' } );
```
 
```
1
2
3
4
5
6
Error: Error: whoops!
```
  `mergeDelayError` is found in the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxKotlin `merge mergeDelayError mergeWith`

     RxKotlin implements this operator as `merge`, `mergeWith`, and `mergeDelayError`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)   Instead of passing multiple Observables (up to nine) into `merge`, you could also pass in a `List<>` (or other Iterable) of Observables, an Array of Observables, or even an Observable that emits Observables, and `merge` will merge their output into the output of a single Observable: 

  ![merge(List)](http://reactivex.io/documentation/operators/images/merge.io.png)  If you pass in an Observable of Observables, you have the option of also passing in a value indicating to `merge` the maximum number of those Observables it should attempt to be subscribed to simultaneously. Once it reaches this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. 

   The instance version of `merge` is `mergeWith`, so, for example, instead of writing `Observable.merge(odds,evens)` you could also write `odds.mergeWith(evens)`. 


 If any of the individual Observables passed into `merge` terminates with an `onError` notification, the Observable produced by `merge` itself will immediately terminate with an `onError` notification. If you would prefer a merge that continues emitting the results of the remaining, error-free Observables before reporting the error, use `mergeDelayError` instead. 

  ![mergeDelayError](http://reactivex.io/documentation/operators/images/mergeDelayError.png)  `mergeDelayError` behaves much like `merge`. The exception is when one of the Observables being merged terminates with an `onError` notification. If this happens with `merge`, the merged Observable will immediately issue an `onError` notification and terminate. `mergeDelayError`, on the other hand, will hold off on reporting the error until it has given any other non-error-producing Observables that it is merging a chance to finish emitting their items, and it will emit those itself, and will only terminate with an `onError` notification when all of the other merged Observables have finished. 


 Because it is possible that more than one of the merged Observables encountered an error, `mergeDelayError` may pass information about *multiple* errors in the `onError` notification (it will never invoke the observer’s `onError` method more than once). For this reason, if you want to know the nature of these errors, you should write your observers’ `onError` methods so that they accept a parameter of the class `CompositeException`. 


 `mergeDelayError` has fewer variants. You cannot pass it an Iterable or Array of Observables, but you can pass it an Observable that emits Observables or between one and nine individual Observables as parameters. There is not an instance method version of `mergeDelayError` as there is for `merge`. 

       ###  RxNET `Merge`

     Rx.NET implements this operator as `Merge`. 

  ![Merge](http://reactivex.io/documentation/operators/images/merge.C.png)  You can pass `Merge` an Array of Observables, an Enumerable of Observables, an Observable of Observables, or two individual Observables. 


 If you pass an Enumerable or Observable of Observables, you have the option of also passing in an integer indicating the maximum number of those Observables it should attempt to be subscribed to simultaneously. Once it reaches this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. 

       ###  RxPHP `merge mergeAll`

       RxPHP implements this operator as `merge`. 

  Combine an Observable together with another Observable by merging their emissions into a single Observable. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/merge/merge.php

$observable       = Rx\Observable::of(42)->repeat();
$otherObservable  = Rx\Observable::of(21)->repeat();
$mergedObservable = $observable
    ->merge($otherObservable)
    ->take(10);

$disposable = $mergedObservable->subscribe($stdoutObserver);
```
  
```
Next value: 42
Next value: 21
Next value: 42
Next value: 21
Next value: 42
Next value: 21
Next value: 42
Next value: 21
Next value: 42
Next value: 21
Complete!
```
      RxPHP also has an operator `mergeAll`. 

  Merges an observable sequence of observables into an observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/merge/merge-all.php

$sources = Rx\Observable::range(0, 3)
    ->map(function ($x) {
        return Rx\Observable::range($x, 3);
    });

$merged = $sources->mergeAll();

$disposable = $merged->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 1
Next value: 2
Next value: 2
Next value: 2
Next value: 3
Next value: 3
Next value: 4
Complete!
```
         ###  RxPY `merge merge_all merge_observable`

     RxPY implements this operator as `merge` and `merge_all`/`merge_observable`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)  You can either pass `merge` a set of Observables as individual parameters, or as a single parameter containing an array of those Observables. 

   ![merge_all](http://reactivex.io/documentation/operators/images/merge_all.png)  `merge_all` and its alias `merge_observable` take as their single parameter an Observable that emits Observables. They merge the emissions of all of these Observables to create their own Observable. 

       ###  Rxrb `merge merge_all merge_concurrent`

     Rx.rb implements this operator as `merge`, `merge_concurrent`, and `merge_all`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)  `merge` merges a second Observable into the one it is operating on to create a new merged Observable. 

   `merge_concurrent` operates on an Observable that emits Observables, merging the emissions from each of these Observables into its own emissions. You can optionally pass it an integer parameter indicating how many of these emitted Observables `merge_concurrent` should try to subscribe to concurrently. Once it reaches this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. The default is 1, which makes it equivalent to `merge_all`. 

  ![merge_all](http://reactivex.io/documentation/operators/images/merge_all.png)  `merge_all` is like `merge_concurrent(1)`. It subscribes to each emitted Observable one at a time, mirroring its emissions as its own, and waiting to subscribe to the next Observable until the present one terminates with an `onCompleted` notification. In this respect it is more like a Concat variant. 

       ###  RxScala `flatten flattenDelayError merge mergeDelayError`

     RxScala implements this operator as `flatten`, `flattenDelayError`, `merge`, and `mergeDelayError`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)  `merge` takes a second Observable as a parameter and merges that Observable with the one the `merge` operator is applied to in order to create a new output Observable. 

   ![mergeDelayError](http://reactivex.io/documentation/operators/images/mergeDelayError.png)  `mergeDelayError` is similar to `merge` except that it will always emit all items from both Observables even if one of the Observables terminates with an `onError` notification before the other Observable has finished emitting items. 

   ![flatten](http://reactivex.io/documentation/operators/images/flatten.png)  `flatten` takes as its parameter an Observable that emits Observables. It merges the items emitted by each of these Observables to create its own single Observable sequence. A variant of this operator allows you to pass in an `Int` indicating the maximum number of these emitted Observables you want `flatten` to try to be subscribed to at any time. It it hits this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. 


 `flattenDelayError` is similar to `flatten` except that it will always emit all items from all of the emitted Observables even if one or more of those Observables terminates with an `onError` notification before the other Observables have finished emitting items. 

       ###  RxSwift `merge`

     RxSwift implements this operator as `merge`. 

  ![merge](http://reactivex.io/documentation/operators/images/merge.png)  `merge` takes as its parameter an Observable that emits Observables. It merges the items emitted by each of these Observables to create its own single Observable sequence. 

  A variant of this operator `merge(maxConcurrent:)` allows you to pass in an `Int` indicating the maximum number of these emitted Observables you want `merge` to try to be subscribed to at any time. If it hits this maximum subscription count, it will refrain from subscribing to any other Observables emitted by the source Observable until such time as one of the already-subscribed-to Observables issues an `onCompleted` notification. 

 #### Sample Code

 
```
let subject1 = PublishSubject()
let subject2 = PublishSubject()

Observable.of(subject1, subject2)
   .merge()
   .subscribe {
       print($0)
   }

subject1.on(.Next(10))
subject1.on(.Next(11))
subject1.on(.Next(12))
subject2.on(.Next(20))
subject2.on(.Next(21))
subject1.on(.Next(14))
subject1.on(.Completed)
subject2.on(.Next(22))
subject2.on(.Completed)
```
 
```
Next(10)
Next(11)
Next(12)
Next(20)
Next(21)
Next(14)
Next(22)
Completed
```
      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/merge.html>

Catch
=====

 
> recover from an onError notification by continuing the sequence without error

  ![Catch](http://reactivex.io/documentation/operators/images/Catch.png)  The Catch operator intercepts an `onError` notification from the source Observable and, instead of passing it through to any observers, replaces it with some other item or sequence of items, potentially allowing the resulting Observable to terminate normally or not to terminate at all. 


 There are several variants of the Catch operator, and a variety of names used by different ReactiveX implementations to describe this operation, as you can see in the sections below. 


 In some ReactiveX implementations, there is an operator called something like “OnErrorResumeNext” that behaves like a Catch variant: specifically reacting to an `onError` notification from the source Observable. In others, there is an operator with that name that behaves more like a Concat variant: performing the concatenation operation regardless of whether the source Observable terminates normally or with an error. This is unfortunate and confusing, but something we have to live with. 

  #### See Also

 * [Concat](concat)
* [Retry](retry)
* [Introduction to Rx: Catch](http://www.introtorx.com/Content/v1.0.10621.0/11_AdvancedErrorHandling.html#Catch)

 Language-Specific Information
-----------------------------

    ###  RxClojure `catch*`

     ![catch*](http://reactivex.io/documentation/operators/images/catchX.png)  RxClojure implements this operator as `catch*`. This operator takes two arguments, both of which are functions of your choosing that take the exception raised by `onError` as their single parameters. The first function is a predicate. If it returns `false`, `catch*` passes the `onError` notification unchanged to its observers. If it returns `true`, however, `catch*` swallows the error, calls the second function (which returns an Observable), and passes along the emissions and notifications from this new Observable to its observers. 


 You may replace the first function parameter (the predicate that evaluates the exception) with a class object representing a variety of exception. If you do this, `catch*` will treat it as equivalent to predicate that performs an `instance?` check to see if the exception from the `onError` notification is an instance of the class object. In other words: 

 #### Sample Code

 
```
(->> my-observable
  (catch* IllegalArgumentException
          (fn [e] (rx/return 1)))
)
```
  is equivalent to: 

 
```
(->> my-observable
  (catch* (fn [e] (-> instance? IllegalArgumentException e))
          (fn [e] (rx/return 1)))
)
```
       ###  RxCpp

     RxCpp does not implement the Catch operator. 

      ###  RxGroovy `onErrorResumeNext onErrorReturn onExceptionResumeNext`

     RxGroovy implements the Catch operator in the same way as does RxJava. There are three distinct operators that provide this functionality: 

  `onErrorReturn` instructs an Observable to emit a particular item when it encounters an error, and then terminate normally `onErrorResumeNext` instructs an Observable to begin emitting a second Observable sequence if it encounters an error `onExceptionResumeNext` instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)  #### `onErrorReturn`

  ![onErrorReturn](http://reactivex.io/documentation/operators/images/onErrorReturn.png)  The `onErrorReturn` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorReturn` will instead emit a specified item and invoke the observer’s `onCompleted` method, as shown in the following sample code: 

 #### Sample Code

 
```
def myObservable = Observable.create({ aSubscriber ->
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('Four');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('Three');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('Two');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('One');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onError();
});

myObservable.onErrorReturn({ return('Blastoff!'); }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
Four
Three
Two
One
Blastoff!
Sequence complete
```
 * Javadoc: [`onErrorReturn(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onErrorReturn(rx.functions.Func1))
  #### `onErrorResumeNext`

  ![onErrorResumeNext](http://reactivex.io/documentation/operators/images/onErrorResumeNext.png)  The `onErrorResumeNext` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorResumeNext` will instead begin mirroring a second, backup Observable, as shown in the following sample code: 

 #### Sample Code

 
```
def myObservable = Observable.create({ aSubscriber ->
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('Three');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('Two');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('One');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onError();
});
def myFallback = Observable.create({ aSubscriber ->
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('0');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('1');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('2');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onCompleted();
});

myObservable.onErrorResumeNext(myFallback).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
Three
Two
One
0
1
2
Sequence complete
```
 * Javadoc: [`onErrorResumeNext(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onErrorResumeNext(rx.functions.Func1))
* Javadoc: [`onErrorResumeNext(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onErrorResumeNext(rx.Observable))
  #### `onExceptionResumeNext`

  ![onExceptionResumeNext](http://reactivex.io/documentation/operators/images/onExceptionResumeNextViaObservable.png)  Much like `onErrorResumeNext` method, this returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, if the Throwable passed to `onError` is an Exception, rather than propagating that Exception to the observer, `onExceptionResumeNext` will instead begin mirroring a second, backup Observable. If the Throwable is not an Exception, the Observable returned by `onExceptionResumeNext` will propagate it to its observer’s `onError` method and will not invoke its backup Observable. 

 * Javadoc: [`onExceptionResumeNext(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onExceptionResumeNext(rx.Observable))
       ###  RxJava 1․x `onErrorResumeNext onErrorReturn onExceptionResumeNext`

     RxJava implements the Catch operator with three distinct operators: 

  `onErrorReturn` instructs an Observable to emit a particular item when it encounters an error, and then terminate normally `onErrorResumeNext` instructs an Observable to begin emitting a second Observable sequence if it encounters an error `onExceptionResumeNext` instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)  #### `onErrorReturn`

  ![onErrorReturn](http://reactivex.io/documentation/operators/images/onErrorReturn.png)  The `onErrorReturn` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorReturn` will instead emit a specified item and invoke the observer’s `onCompleted` method. 

 * Javadoc: [`onErrorReturn(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onErrorReturn(rx.functions.Func1))
  #### `onErrorResumeNext`

  ![onErrorResumeNext](http://reactivex.io/documentation/operators/images/onErrorResumeNext.png)  The `onErrorResumeNext` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorResumeNext` will instead begin mirroring a second, backup Observable. 

 * Javadoc: [`onErrorResumeNext(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onErrorResumeNext(rx.functions.Func1))
* Javadoc: [`onErrorResumeNext(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onErrorResumeNext(rx.Observable))
  #### `onExceptionResumeNext`

  ![onExceptionResumeNext](http://reactivex.io/documentation/operators/images/onExceptionResumeNextViaObservable.png)  Much like `onErrorResumeNext` method, this returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, if the Throwable passed to `onError` is an Exception, rather than propagating that Exception to the observer, `onExceptionResumeNext` will instead begin mirroring a second, backup Observable. If the Throwable is not an Exception, the Observable returned by `onExceptionResumeNext` will propagate it to its observer’s `onError` method and will not invoke its backup Observable. 

 * Javadoc: [`onExceptionResumeNext(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#onExceptionResumeNext(rx.Observable))
       ###  RxJS `catch onErrorResumeNext`

     RxJS implements the Catch operator with two distinct operators: 

  `catch` instructs an Observable to begin emitting a second Observable sequence if it encounters an error `onErrorResumeNext` instructs an Observable to begin emitting a second Observable sequence if it encounters an error or if the source Observable terminates normally  #### `catch`

  ![catch](http://reactivex.io/documentation/operators/images/catch.js.png)  `catch` is found in the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

   #### `onErrorResumeNext`

  ![onErrorResumeNext](http://reactivex.io/documentation/operators/images/onErrorResumeNext.js.png)  This implementation borrows the confusing nomenclature from Rx.NET, in which `onErrorResumeNext` switches to a back-up Observable both on an error *and* on a normal, error-free termination of the source Observable. 

  `onErrorResumeNext` is found in the following distributions: 

 * `rx.js`
* `rx.compat.js`

        ###  RxKotlin `onErrorResumeNext onErrorReturn onExceptionResumeNext`

     RxKotlin implements the Catch operator in the same way as does RxJava. There are three distinct operators that provide this functionality: 

  `onErrorReturn` instructs an Observable to emit a particular item when it encounters an error, and then terminate normally `onErrorResumeNext` instructs an Observable to begin emitting a second Observable sequence if it encounters an error `onExceptionResumeNext` instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)  #### `onErrorReturn`

  ![onErrorReturn](http://reactivex.io/documentation/operators/images/onErrorReturn.png)  The `onErrorReturn` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorReturn` will instead emit a specified item and invoke the observer’s `onCompleted` method. 

  #### `onErrorResumeNext`

  ![onErrorResumeNext](http://reactivex.io/documentation/operators/images/onErrorResumeNext.png)  The `onErrorResumeNext` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorResumeNext` will instead begin mirroring a second, backup Observable. 

  #### `onExceptionResumeNext`

  ![onExceptionResumeNext](http://reactivex.io/documentation/operators/images/onExceptionResumeNextViaObservable.png)  Much like `onErrorResumeNext` method, this returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, if the Throwable passed to `onError` is an Exception, rather than propagating that Exception to the observer, `onExceptionResumeNext` will instead begin mirroring a second, backup Observable. If the Throwable is not an Exception, the Observable returned by `onExceptionResumeNext` will propagate it to its observer’s `onError` method and will not invoke its backup Observable. 

       ###  RxNET `Catch OnErrorResumeNext`

     Rx.NET implements the Catch operator with two distinct operators: 

  `Catch` instructs an Observable to begin emitting a second Observable sequence if it encounters an error `OnErrorResumeNext` instructs an Observable to begin emitting a second Observable sequence if it encounters an error or if the source Observable terminates normally  #### `Catch`

  ![Catch](http://reactivex.io/documentation/operators/images/Catch.png)  The `Catch` operator has a variant that allows you to specify which sort of Exception you want to catch. If you use that variant of the operator, any other Exceptions will be passed through to the observer as if the `Catch` operator had not been applied. 

  #### `OnErrorResumeNext`

  ![OnErrorResumeNext](http://reactivex.io/documentation/operators/images/OnErrorResumeNext.net.png)  This implementation introduces a confusing nomenclature, in which in spite of its name `OnErrorResumeNext` switches to a back-up Observable both on an error *and* on a normal, error-free termination of the source Observable. It is therefore more like a concatenation operator. 

       ###  RxPHP `catch`

       RxPHP implements this operator as `catch`. 

  Continues an observable sequence that is terminated by an exception with the next observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/catch/catch.php

$obs2 = Rx\Observable::of(42);

$source = \Rx\Observable::error(new Exception('Some error'))
    ->catch(function (Throwable $e, \Rx\Observable $sourceObs) use ($obs2) {
        return $obs2;
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Complete!
```
         ###  RxPY `catch_exception on_error_resume_next`

     RxPY implements the Catch operator with two distinct operators: 

  `catch_exception` instructs an Observable, if it encounters an error, to begin emitting items from a set of other Observables, one Observable at a time, until one of those Observables terminates successfully `on_error_resume_next` instructs an Observable to concatenate items emitted by a set of other Observables, one Observable at a time, regardless of whether the source Observable or any subsequent Observable terminates with an error  #### `catch_exception`

  ![catch_exception](http://reactivex.io/documentation/operators/images/catch_exception.png)  You may pass `catch_exception` a set of back-up Observables either as individual function parameters or as a single array of Observables. If it encounters an `onError` notification from the source Observable, it will subscribe to and begin mirroring the first of these back-up Observables. If this back-up Observable itself issues an `onError` notification, `catch_exception` will swallow it and switch over to the next back-up Observable. If any of these Observables issues an `onCompleted` notification, `catch_exception` will pass this along and will stop. 

  #### `on_error_resume_next`

  ![on_error_resume_next](http://reactivex.io/documentation/operators/images/on_error_resume_next.png)  You may pass `on_error_resume_next` a set of back-up Observables either as individual function parameters, as a single array of Observables, or as a factory function that generates Observables. When the source Observable terminates, whether normally or with an error, `on_error_resume_next` will subscribe to and begin mirroring the first of these back-up Observables, and then will recursively continue this concatenation process for each additional Observable until there are no more Observables to mirror, at which time it will pass on the `onError` or `onCompleted` notification from the last of these Observables. 

       ###  Rxrb `on_error_resume_next rescue_error`

     Rx.rb implements the Catch operator with two distinct operators: 

  `rescue_error` instructs an Observable to begin emitting items from another Observable, or from an Observable returned from an action, if it encounters an error `on_error_resume_next` instructs an Observable to concatenate items emitted by another Observable to the sequence emitted by the source Observable, regardless of whether the source Observable terminates normally or with an error  #### `rescue_error`

  ![rescue_error](http://reactivex.io/documentation/operators/images/rescue_error.png)  You may pass `rescue_error` either an Observable or a factory action that generates an Observable. 

  #### `on_error_resume_next`

  ![on_error_resume_next](http://reactivex.io/documentation/operators/images/on_error_resume_next.png)  In Rx.rb, `on_error_resume_next` inherits the misleading nomenclature from Rx.NET in that it concatenates the second Observable sequence to the source sequence whether that source sequence terminates normally or with an error. 

       ###  RxScala `onErrorFlatMap onErrorResumeNext onErrorReturn onExceptionResumeNext`

     Rx.rb implements the Catch operator with four distinct operators: 

  `onErrorFlatMap` replaces all `onError` notifications from a misbehaving Observable into the emissions from a secondary Observable `onErrorResumeNext` instructs an Observable to begin emitting a second Observable sequence if it encounters an error `onErrorReturn` instructs an Observable to emit a particular item when it encounters an error, and then terminate normally `onExceptionResumeNext` instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)  #### `onErrorFlatMap`

  ![onErrorFlatMap](http://reactivex.io/documentation/operators/images/onErrorFlatMap.png)  `onErrorFlatMap` handles a special case: a source Observable that is noncompliant with [the Observable contract](../contract) in such a way that it may interleave `onError` notifications with its emissions without terminating. This operator allows you to replace those `onError` notifications with the emissions of an Observable of your choosing without unsubscribing from the source, so that any future items emitted from the source will be passed along to observers as though the sequence had not been interrupted with an `onError` notification. 


 Because `onErrorFlatMap` is designed to work with pathological source Observables that do not terminate after issuing an error, it is mostly useful in debugging/testing scenarios. 

   ![unintuitive onErrorFlatMap and Merge interaction](http://reactivex.io/documentation/operators/images/onErrorFlatMap.withMerge.png)  Note that you should apply `onErrorFlatMap` directly to the pathological source Observable, and not to that Observable after it has been modified by additional operators, as such operators may effectively renormalize the source Observable by unsubscribing from it immediately after it issues an error. Above, for example, is an illustration showing how `onErrorFlatMap` will respond to two error-generating Observables that have been merged by the [Merge](merge) operator: 


 Note that `onErrorFlatMap` will not react to both errors generated by both Observables, but only to the single error passed along by `merge`. 

  #### `onErrorResumeNext`

  ![onErrorResumeNext](http://reactivex.io/documentation/operators/images/onErrorResumeNext.png)  The `onErrorResumeNext` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorResumeNext` will instead begin mirroring a second, backup Observable. 

  #### `onErrorReturn`

  ![onErrorReturn](http://reactivex.io/documentation/operators/images/onErrorReturn.png)  The `onErrorReturn` method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, rather than propagating that error to the observer, `onErrorReturn` will instead emit a specified item and invoke the observer’s `onCompleted` method. 

  #### `onExceptionResumeNext`

  ![onExceptionResumeNext](http://reactivex.io/documentation/operators/images/onExceptionResumeNextViaObservable.png)  Much like `onErrorResumeNext` method, this returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes `onError` in which case, if the Throwable passed to `onError` is an Exception, rather than propagating that Exception to the observer, `onExceptionResumeNext` will instead begin mirroring a second, backup Observable. If the Throwable is not an Exception, the Observable returned by `onExceptionResumeNext` will propagate it to its observer’s `onError` method and will not invoke its backup Observable. 

     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/catch.html>

All
===

 
> determine whether all items emitted by an Observable meet some criteria

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#every)  Pass a predicate function to the All operator that accepts an item emitted by the source Observable and returns a boolean value based on an evaluation of that item. All returns an Observable that emits a single boolean value: `true` if and only if the source Observable terminates normally and every item emitted by the source Observable evaluated as `true` according to this predicate; `false` if any item emitted by the source Observable evaluates as `false` according to this predicate. 

  #### See Also

 * [Introduction to Rx: All](http://www.introtorx.com/Content/v1.0.10621.0/06_Inspection.html#All)
* [RxMarbles: `every`](http://rxmarbles.com/#every)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `all`

     ![all](http://reactivex.io/documentation/operators/images/all.png)  RxGroovy implements this operator as `all`. It does not by default operate on any particular [Scheduler](../scheduler). The following example shows how to use this operator: 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5]);

println("all even?" )
numbers.all({ 0 == (it % 2) }).subscribe({ println(it); });

println("all positive?");
numbers.all({ 0 < it }).subscribe({ println(it); });
```
 
```
all even? 
false
all positive? 
true
```
 * Javadoc: [`all(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#all(rx.functions.Func1))
       ###  RxJava 1․x `all`

     ![all](http://reactivex.io/documentation/operators/images/all.png)  RxJava 1.x implements this operator as `all`. It does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`all(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#all(rx.functions.Func1))
       ###  RxJava 2․x `all`

     ![all](http://reactivex.io/documentation/operators/images/all.png)  RxJava 2.x implements this operator as `all`. It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`all(Predicate)`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html#all(io.reactivex.functions.Predicate))
       ###  RxJS `every jortSort jortSortUntil`

     ![every](http://reactivex.io/documentation/operators/images/every.png)  RxJS implements this operator as `every`. The following example shows how to use this operator: 

 #### Sample Code

 
```
var source = Rx.Observable.of(1,2,3,4,5)
  .every(function (x) {
    return x < 6;
  });

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: true
Completed
```
  `every` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    There is also a `jortSort` operator that performs a test on the entire sequence of items emitted by the source Observable. If those items are emitted in sorted order, upon the successful completion of the source Observable, the Observable returned from `jortSort` will emit `true` and then complete. If any of the items emitted by the source Observable is out of sort order, upon the successful completion of the source Observable, the Observable returned from `jortSort` will emit `false` and then complete. 


 There is also a `jortSortUntil` operator. It does not wait until the source Observable completes to evaluate its sequence for sortedness, as `jortSort` does, but waits until a second Observable emits an item to do so. 

 #### See also

 * [jort.technology](http://jort.technology)

 #### Sample Code

 
```
var source = Rx.Observable.of(1,2,3,4) // already sorted
               .jortSort();

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
```
 
```
Next: true
Completed
```
 
```
var source = Rx.Observable.of(3,1,2,4) // not sorted
               .jortSort();

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
```
 
```
Next: false
Completed
```
 
```
var just = Rx.helpers.just;

var source = Rx.Observable.of(1,2,3,4) // already sorted
               .flatmap(function (x) {
                 return Rx.Observable.timer(1000).map(just(x));
               }).jortSortUntil(Rx.Observable.timer(3000);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
```
 
```
Next: true
Completed
```
 
```
var just = Rx.helpers.just;

var source = Rx.Observable.of(3,1,2,4) // not sorted
               .flatmap(function (x) {
                 return Rx.Observable.timer(1000).map(just(x));
               }).jortSortUntil(Rx.Observable.timer(3000);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
```
 
```
Next: false
Completed
```
  `jortSort` and `jortSortUntil` are found in the following distribution: 

 * `rx.sorting.js`

  They require one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/all.html>

Amb
===

 
> given two or more source Observables, emit all of the items from only the first of these Observables to emit an item or notification

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#amb)  When you pass a number of source Observables to Amb, it will pass through the emissions and notifications of exactly one of these Observables: the first one that sends a notification to Amb, either by emitting an item or sending an `onError` or `onCompleted` notification. Amb will ignore and discard the emissions and notifications of all of the other source Observables. 

  #### See Also

 * [RxMarbles: `amb`](http://rxmarbles.com/#amb)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `amb ambWith`

     ![amb](http://reactivex.io/documentation/operators/images/amb.png)  RxGroovy implements this operator as `amb`. It takes up to nine Observables as individual parameters, or a single Iterable of Observables. There is also an instance version of the operator, `ambWith`, so that, for example, instead of writing `Observable.amb(o1,o2)` you could also write `o1.ambWith(o2)` for the same effect. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`amb(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#amb(java.lang.Iterable))
* Javadoc: [`amb(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#amb(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observable parameters)
* Javadoc: [`ambWith(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#ambWith(rx.Observable))
       ###  RxJava 1․x `amb ambWith`

     ![amb](http://reactivex.io/documentation/operators/images/amb.png)  RxJava 1.x implements this operator as `amb`. It takes up to nine Observables as individual parameters, or a single Iterable of Observables. There is also an instance version of the operator, `ambWith`, so that, for example, instead of writing `Observable.amb(o1,o2)` you could also write `o1.ambWith(o2)` for the same effect. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`amb(Iterable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#amb(java.lang.Iterable))
* Javadoc: [`amb(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#amb(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observable parameters)
* Javadoc: [`ambWith(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#ambWith(rx.Observable))
       ###  RxJava 2․x `amb ambArray ambWith`

     ![amb](http://reactivex.io/documentation/operators/images/amb.png)  RxJava 2.x implements this operator as `amb`. It takes an Iterable of Observables as its parameter. You can also use `ambArray` to pass an array of Observables. There is also an instance version of the operator, `ambWith`, so that, for example, instead of writing `Observable.ambArray([o1,o2])` you could also write `o1.ambWith(o2)` for the same effect. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`amb(Iterable)`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html#amb(java.lang.Iterable))
* Javadoc: [`ambArray(Iterable)`](#)
* Javadoc: [`ambWith(Observable)`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Observable.html#ambWith(io.reactivex.ObservableSource))
       ###  RxJS `amb`

     ![amb](http://reactivex.io/documentation/operators/images/amb.png)  RxJS implements this operator as `amb`. It takes a variable number of parameters, which may be either Observables or Promises (or combinations of the two). 

 #### Sample Code

 
```
/* Using Observable sequences */
var source = Rx.Observable.amb(
    Rx.Observable.timer(500).select(function () { return 'foo'; }),
    Rx.Observable.timer(200).select(function () { return 'bar'; })
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: bar
Completed
```
 
```
/* Using Promises and Observables */
var source = Rx.Observable.amb(
    RSVP.Promise.resolve('foo')
    Rx.Observable.timer(200).select(function () { return 'bar'; })
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: foo
Completed
```
       ###  RxPHP `race`

       RxPHP implements this operator as `race`. 

  Propagates the observable sequence that reacts first. Also known as 'amb'. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/race/race.php

$source = Rx\Observable::race(
    [
        Rx\Observable::timer(500)->map(function () {
            return 'foo';
        }),
        Rx\Observable::timer(200)->map(function () {
            return 'bar';
        })
    ]
);

$source->subscribe($stdoutObserver);
```
  
```
Next value: bar
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/amb.html>

Contains
========

 
> determine whether an Observable emits a particular item or not

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#contains)  Pass the Contains operator a particular item, and the Observable it returns will emit `true` if that item is emitted by the source Observable, or `false` if the source Observable terminates without emitting that item. 

   A related operator, IsEmpty returns an Observable that emits `true` if and only if the source Observable completes without emitting any items. It emits `false` if the source Observable emits an item. 

 #### See Also

 * [All](all)
* [Introduction to Rx: Contains](http://www.introtorx.com/Content/v1.0.10621.0/06_Inspection.html#Contains)
* [RxMarbles: `contains`](http://rxmarbles.com/#contains)
* [RxMarbles: `some`](http://rxmarbles.com/#some)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `contains exists isEmpty`

     ![contains](http://reactivex.io/documentation/operators/images/contains.png)  RxGroovy implements this operator as `contains`. It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`contains(Object)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#contains(java.lang.Object))
   ![exists](http://reactivex.io/documentation/operators/images/exists.png)  RxGroovy also implements the `exists` operator. It is similar to `contains` but tests items emitted by the source Observable against a predicate function you supply, rather than testing them for identity with a particular object. The Observable returned from `exists` will return `true` if the source Observable emits an item that satisfies your predicate function, and `false` if it completes without emitting such an item. 


 It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`exists(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#exists(rx.functions.Func1))
   ![isEmpty](http://reactivex.io/documentation/operators/images/isEmpty.png)  RxGroovy also implements the `isEmpty` operator. The Observable returned from `isEmpty` will return `false` if the source Observable emits an item, and `true` if it completes without emitting an item. 


 It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`isEmpty()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#isEmpty())
       ###  RxJava 1․x `contains exists isEmpty`

     ![contains](http://reactivex.io/documentation/operators/images/contains.png)  RxJava implements this operator as `contains`. It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`contains(Object)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#contains(java.lang.Object))
   ![exists](http://reactivex.io/documentation/operators/images/exists.png)  RxJava also implements the `exists` operator. It is similar to `contains` but tests items emitted by the source Observable against a predicate function you supply, rather than testing them for identity with a particular object. The Observable returned from `exists` will return `true` if the source Observable emits an item that satisfies your predicate function, and `false` if it completes without emitting such an item. 


 It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`exists(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#exists(rx.functions.Func1))
   ![isEmpty](http://reactivex.io/documentation/operators/images/isEmpty.png)  RxJava also implements the `isEmpty` operator. The Observable returned from `isEmpty` will return `false` if the source Observable emits an item, and `true` if it completes without emitting an item. 


 It does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`isEmpty()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#isEmpty())
       ###  RxJava 2․x `any contains isEmpty`

     ###  RxJS `contains findIndex indexOf isEmpty`

     ![contains](http://reactivex.io/documentation/operators/images/contains.png)  The `contains` operator in RxJS takes an optional second parameter: a zero-based index into the source Observable’s sequence at which to start searching for the item. 

 #### Sample Code

 
```
/* Without an index */
var source = Rx.Observable.of(42)
  .contains(42);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: true
Completed
```
 
```
/* With an index */
var source = Rx.Observable.of(1,2,3)
  .contains(2, 1);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: true
Completed
```
  `contains` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![indexOf](http://reactivex.io/documentation/operators/images/indexOf.png)  The `indexOf` operator in RxJS is similar to `contains` but rather than returning an Observable that emits `true` or `false` it returns an Observable that emits the index of the item in the source Observable sequence, or `−1` if no such item was emitted. 


 The `indexOf` operator takes an optional second parameter: a zero-based index into the source Observable’s sequence at which to start searching for the item. The index value that the resulting Observable emits will be relative to this start point, not to the beginning of the sequence. 

 #### Sample Code

 
```
/* Without an index */
var source = Rx.Observable.of(42)
  .indexOf(42);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: 0 
Completed
```
 
```
/* With an index */
var source = Rx.Observable.of(1,2,3)
  .indexOf(2, 1);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
```
 
```
Next: 0 
Completed
```
  `indexOf` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![findIndex](http://reactivex.io/documentation/operators/images/findIndex.png)  The `findIndex` operator in RxJS takes as its parameter a predicate function. It returns an Observable that emits either a single number — the zero-based index of the first item in the source Observable sequence that matches the predicate — or `−1` if no such item matches. 


 The predicate function takes three parameters: 


* the item emitted by the source Observable
* the zero-based index of that item
* the source Observable itself


 You can also pass an object to `findIndex` as an optional second parameter, and that object will be available to the predicate function as “`this`”. 

 #### Sample Code

 
```
/* Found an element */
var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .findIndex(function (x, i, obs) {
        return x === 1;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Completed
```
 
```
/* Not found */
var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .findIndex(function (x, i, obs) {
        return x === 5;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: -1
Completed
```
  `findIndex` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![isEmpty](http://reactivex.io/documentation/operators/images/isEmpty.png)  RxJS also implements the `isEmpty` operator. The Observable returned from `isEmpty` will return `false` if the source Observable emits an item, and `true` if it completes without emitting an item. 

 #### Sample Code

 
```
/* Not empty */
var source = Rx.Observable.range(0, 5)
    .isEmpty()

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: false
Completed
```
 
```
/* Empty */
var source = Rx.Observable.empty()
    .isEmpty()

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: true
Completed
```
  `isEmpty` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following distributions: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `isEmpty`

       RxPHP implements this operator as `isEmpty`. 

  If the source Observable is empty it returns an Observable that emits true, otherwise it emits false. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/isEmpty/isEmpty.php

$source = \Rx\Observable::emptyObservable()
    ->isEmpty();

$source->subscribe($stdoutObserver);
```
  
```
Next value: 1
Complete!
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/isEmpty/isEmpty-false.php

$source = \Rx\Observable::just(1)
    ->isEmpty();

$source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/contains.html>

DefaultIfEmpty
==============

 
> emit items from the source Observable, or a default item if the source Observable emits nothing

  ![DefaultIfEmpty](http://reactivex.io/documentation/operators/images/defaultIfEmpty.c.png)  The DefaultIfEmpty operator simply mirrors the source Observable exactly if the source Observable emits any items. If the source Observable terminates normally (with an `onComplete`) without emitting any items, the Observable returned from DefaultIfEmpty will instead emit a default item of your choosing before it too completes. 

  #### See Also

 * [Introduction to Rx: DefaultIfEmpty](http://www.introtorx.com/Content/v1.0.10621.0/06_Inspection.html#DefaultIfEmpty)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `defaultIfEmpty switchIfEmpty`

     ![defaultIfEmpty](http://reactivex.io/documentation/operators/images/defaultIfEmpty.png)  RxGroovy implements this operator as `defaultIfEmpty`. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`defaultIfEmpty(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#defaultIfEmpty(T))
   There is also a new operator in RxGroovy 1.1 called `switchIfEmpty` that, rather than emitting a backup *value* if the source Observable terminates without having emitted any items, it emits the emissions from a backup *Observable*. 

      ###  RxJava 1․x `defaultIfEmpty switchIfEmpty`

     ![defaultIfEmpty](http://reactivex.io/documentation/operators/images/defaultIfEmpty.png)  RxJava implements this operator as `defaultIfEmpty`. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`defaultIfEmpty(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#defaultIfEmpty(T))
   There is also a new operator in RxJava 1.1 called `switchIfEmpty` that, rather than emitting a backup *value* if the source Observable terminates without having emitted any items, it emits the emissions from a backup *Observable*. 

 #### Sample Code

 
```
Observable.empty().defaultIfEmpty(10).subscribe(
    val -> System.out.println("next: " + val),
    err -> System.err.println(err) ,
    () -> System.out.println("completed")
);
```
 

```
next: 10
completed
```
       ###  RxJava 2․x `defaultIfEmpty switchIfEmpty`

     ![defaultIfEmpty](http://reactivex.io/documentation/operators/images/defaultIfEmpty.png)  RxJava implements this operator as `defaultIfEmpty`. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`defaultIfEmpty(T)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#defaultIfEmpty(T))
  #### Sample Code

 
```
Flowable.empty().defaultIfEmpty(10).subscribe(
    val -> System.out.println("next: " + val),
    err -> System.err.println(err) ,
    () -> System.out.println("completed")
);
```
 

```
next: 10
completed
```
       ###  RxJS `defaultIfEmpty`

     ![defaultIfEmpty](http://reactivex.io/documentation/operators/images/defaultIfEmpty.png)  RxJS implements `defaultIfEmpty`, but the parameter that sets the default value is optional. If you do not pass this default value, `defaultIfEmpty` will emit a “`null`” if the source Observable completes without emitting anything. (Note that an emission of a “`null`” is *not* the same as no emission.) 

 #### Sample Code

 
```
/* Without a default value */
var source = Rx.Observable.empty().defaultIfEmpty();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x.toString()); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: null
Completed
```
 
```
/* With a defaultValue */
var source = Rx.Observable.empty().defaultIfEmpty(false);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x.toString()); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: false
Completed
```
  `defaultIfEmpty` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `defaultIfEmpty`

       RxPHP implements this operator as `defaultIfEmpty`. 

  Returns the specified value of an observable if the sequence is empty. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/defaultIfEmpty/defaultIfEmpty.php

$source = \Rx\Observable::empty()->defaultIfEmpty(Rx\Observable::of('something'));

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: something
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/defaultifempty.html>

SequenceEqual
=============

 
> determine whether two Observables emit the same sequence of items

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#sequenceEqual)  Pass SequenceEqual two Observables, and it will compare the items emitted by each Observable, and the Observable it returns will emit `true` only if both sequences are the same (the same items, in the same order, with the same termination state). 

  #### See Also

 * [Introduction to Rx: SequenceEqual](http://www.introtorx.com/Content/v1.0.10621.0/06_Inspection.html#SequenceEqual)
* [RxMarbles: `sequenceEqual`](http://rxmarbles.com/#sequenceEqual)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `sequenceEqual`

     ![sequenceEqual](http://reactivex.io/documentation/operators/images/sequenceEqual.png)  Pass `sequenceEqual` two Observables, and it will compare the items emitted by each Observable, and the Observable it returns will emit `true` only if both sequences terminate normally after emitting the same sequence of items in the same order; otherwise it will emit `false`. You can optionally pass a third parameter: a function that accepts two items and returns `true` if they are equal according to a standard of your choosing. 

 #### Sample Code

 
```
def firstfour = Observable.from([1, 2, 3, 4]);
def firstfouragain = Observable.from([1, 2, 3, 4]);
def firstfive = Observable.from([1, 2, 3, 4, 5]);
def firstfourscrambled = Observable.from([3, 2, 1, 4]);

println('firstfour == firstfive?');
Observable.sequenceEqual(firstfour, firstfive).subscribe({ println(it); });
println('firstfour == firstfouragain?');
Observable.sequenceEqual(firstfour, firstfouragain).subscribe({ println(it); });
println('firstfour == firstfourscrambled?');
Observable.sequenceEqual(firstfour, firstfourscrambled).subscribe({ println(it); });
```
 
```
firstfour == firstfive?
false
firstfour == firstfouragain?
true
firstfour == firstfourscrambled?
false
```
  This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`sequenceEqual(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sequenceEqual(rx.Observable,%20rx.Observable))
* Javadoc: [`sequenceEqual(Observable,Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sequenceEqual(rx.Observable,%20rx.Observable,%20rx.functions.Func2))
       ###  RxJava 1․x `sequenceEqual`

     ![sequenceEqual](http://reactivex.io/documentation/operators/images/sequenceEqual.png)  Pass `sequenceEqual` two Observables, and it will compare the items emitted by each Observable, and the Observable it returns will emit `true` only if both sequences terminate normally after emitting the same sequence of items in the same order; otherwise it will emit `false`. You can optionally pass a third parameter: a function that accepts two items and returns `true` if they are equal according to a standard of your choosing. 


 This operator does not by default operate on any particular [Scheduler](../scheduler). 


* Javadoc: [`sequenceEqual(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sequenceEqual(rx.Observable,%20rx.Observable))
* Javadoc: [`sequenceEqual(Observable,Observable,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#sequenceEqual(rx.Observable,%20rx.Observable,%20rx.functions.Func2))
       ###  RxJS `sequenceEqual`

     ![sequenceEqual](http://reactivex.io/documentation/operators/images/sequenceEqual.png)  In RxJS, `sequenceEqual` is a method of a particular Observable instance, so you pass it exactly one other Observable to compare the instance to. You can optionally pass a second parameter: a function that accepts two items and returns `true` if they are equal according to a standard of your choosing. `sequenceEqual` returns an Observable that will emit a `true` if the two Observables emit the same set of items in the same order before completing, or a `false` otherwise. 

 #### Sample Code

 
```
var source1 = Rx.Observable.return(42);
var source2 = Rx.Observable.return(42);

var source = source1.sequenceEqual(source2);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: true
Completed
```
  `sequenceEqual` is found in each of the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  `sequenceEqual` requires one of the following distributions: 

 * `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/sequenceequal.html>

SkipUntil
=========

 
> discard items emitted by an Observable until a second Observable emits an item

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#skipUntil)  The SkipUntil subscribes to the source Observable, but ignores its emissions until such time as a second Observable emits an item, at which point SkipUntil begins to mirror the source Observable. 

  #### See Also

 * [Skip](skip)
* [SkipLast](skiplast)
* [SkipWhile](skipwhile)
* [Take](take)
* [TakeLast](takelast)
* [TakeUntil](takeuntil)
* [TakeWhile](takewhile)
* [Introduction to Rx: SkipUntil and TakeUntil](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipUntilTakeUntil)
* [RxMarbles: `skipUntil`](http://rxmarbles.com/#skipUntil)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `skipUntil`

     ![skipUntil](http://reactivex.io/documentation/operators/images/skipUntil.png)  In RxGroovy, this operator is implemented as `skipUntil`. 


 `skipUntil` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skipUntil(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipUntil(rx.Observable))
       ###  RxJava 1․x `skipUntil`

     ![skipUntil](http://reactivex.io/documentation/operators/images/skipUntil.png)  In RxJava, this operator is implemented as `skipUntil`. 


 `skipUntil` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skipUntil(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipUntil(rx.Observable))
       ###  RxJS `skipUntil`

     ![skipUntil](http://reactivex.io/documentation/operators/images/skipUntil.png)  RxJS implements the `skipUntil` operator. You can pass it either an Observable or a `Promise` that it will monitor for an item that triggers `skipUntil` to begin mirroring the source Observable. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .skipUntil(Rx.Observable.timer(5000));

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 6
Next: 7
Next: 8
Completed
```
  `skipUntil` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    There is also a `skipUntilWithTime` operator to which you can pass an absolute time or an initial duration in place of an Observable, but this is described on the [Skip](skip) operator page. 

      ###  RxPHP `skipUntil`

       RxPHP implements this operator as `skipUntil`. 

  Returns the values from the source observable sequence only after the other observable sequence produces a value. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/skip/skipUntil.php

$observable = Rx\Observable::interval(1000)
    ->skipUntil(\Rx\Observable::timer(5000))
    ->take(3);

$observable->subscribe($stdoutObserver);
```
  
```
Next value: 4
Next value: 5
Next value: 6
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/skipuntil.html>

SkipWhile
=========

 
> discard items emitted by an Observable until a specified condition becomes false

  ![SkipWhile](http://reactivex.io/documentation/operators/images/skipWhile.c.png)  The SkipWhile subscribes to the source Observable, but ignores its emissions until such time as some condition you specify becomes false, at which point SkipWhile begins to mirror the source Observable. 

  #### See Also

 * [Skip](skip)
* [SkipLast](skiplast)
* [SkipUntil](skipuntil)
* [Take](take)
* [TakeLast](takelast)
* [TakeUntil](takeuntil)
* [TakeWhile](takewhile)
* [Introduction to Rx: SkipWhile and TakeWhile](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipWhileTakeWhile)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `skipWhile`

     ![skipWhile](http://reactivex.io/documentation/operators/images/skipWhile.png)  The `skipWhile` operator returns an Observable that discards items emitted by the source Observable until such time as a function, applied to an item emitted by that Observable, returns `false`, whereupon the new Observable emits that item and the remainder of the items emitted by the source Observable. 

 
```
numbers = Observable.from( [1, 2, 3, 4, 5, 6, 7, 8, 9] );

numbers.skipWhile({ (5 != it) }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
5
6
7
8
9
Sequence complete
```
  `skipWhile` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skipWhile(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipWhile(rx.functions.Func1))
       ###  RxJava 1․x `skipWhile`

     ![skipWhile](http://reactivex.io/documentation/operators/images/skipWhile.png)  The `skipWhile` operator returns an Observable that discards items emitted by the source Observable until such time as a function, applied to an item emitted by that Observable, returns `false`, whereupon the new Observable emits that item and the remainder of the items emitted by the source Observable. 


 `skipWhile` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`skipWhile(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#skipWhile(rx.functions.Func1))
       ###  RxJS `skipWhile`

     ![skipWhile](http://reactivex.io/documentation/operators/images/skipWhile.png)  RxJS implements the `skipWhile` operator. You pass it a function that governs the skipping process. `skipWhile` calls that function for each item emitted by the source Observable until such time as the function returns `false`, whereupon `skipWhile` begins mirroring the source Observable (starting with that item). The function takes three parameters: 

 1. the emitted item
2. the zero-based index of that item in the sequence of emissions
3. the source Observable

  You may optionally pass a second parameter to `skipWhile`. If so, that item will also be available to your predicate function as “`this`”. 

 #### Sample Code

 
```
var source = Rx.Observable.range(1, 5)
    .skipWhile(function (x) { return x < 3; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 3
Next: 4
Next: 5
Completed
```
  `skipWhile` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `skipWhile skipWhileWithIndex`

       RxPHP implements this operator as `skipWhile`. 

  Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/skip/skipWhile.php

$observable = Rx\Observable::range(1, 5)
    ->skipWhile(function ($x) {
        return $x < 3;
    });

$observable->subscribe($stdoutObserver);
```
  
```
Next value: 3
Next value: 4
Next value: 5
Complete!
```
      RxPHP also has an operator `skipWhileWithIndex`. 

  Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. The element's index is used in the logic of the predicate function. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/skip/skipWhileWithIndex.php

$observable = Rx\Observable::range(1, 5)
    ->skipWhileWithIndex(function ($i, $value) {
        return $i < 3;
    });

$observable->subscribe($stdoutObserver);
```
  
```
Next value: 4
Next value: 5
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/skipwhile.html>

TakeUntil
=========

 
> discard any items emitted by an Observable after a second Observable emits an item or terminates

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#takeUntil)  The TakeUntil subscribes and begins mirroring the source Observable. It also monitors a second Observable that you provide. If this second Observable emits an item or sends a termination notification, the Observable returned by TakeUntil stops mirroring the source Observable and terminates. 

  #### See Also

 * [Skip](skip)
* [SkipLast](skiplast)
* [SkipUntil](skipuntil)
* [SkipWhile](skipwhile)
* [Take](take)
* [TakeLast](takelast)
* [TakeWhile](takewhile)
* [Introduction to Rx: SkipUntil and TakeUntil](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipUntilTakeUntil)
* [RxMarbles: `takeUntil`](http://rxmarbles.com/#takeUntil)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `takeUntil`

     ![takeUntil](http://reactivex.io/documentation/operators/images/takeUntil.png)  In RxGroovy, this operator is implemented as `takeUntil`. Note that the second Observable can cause `takeUntil` to quit emitting items either by emitting an item or by issuing an `onError` or `onCompleted` notification. 


 `takeUntil` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`takeUntil(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeUntil(rx.Observable))
   ![takeUntil](http://reactivex.io/documentation/operators/images/takeUntil.p.png)  A second version of this operator was released in RxGroovy 1.1. It uses a predicate function that evaluates the items emitted by the source Observable, rather than a second Observable, to terminate the resulting Observable sequence. In this way, it behaves in a similar way to [TakeWhile](takewhile). 

 * Javadoc: [`takeUntil(Func1)` (RxGroovy 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeUntil(rx.functions.Func1))
       ###  RxJava 1․x `takeUntil`

     ![takeUntil](http://reactivex.io/documentation/operators/images/takeUntil.png)  In RxJava, this operator is implemented as `takeUntil`. Note that the second Observable can cause `takeUntil` to quit emitting items either by emitting an item or by issuing an `onError` or `onCompleted` notification. 


 `takeUntil` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`takeUntil(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeUntil(rx.Observable))
   ![takeUntil](http://reactivex.io/documentation/operators/images/takeUntil.p.png)  A second version of this operator was released in RxJava 1.1. It uses a predicate function that evaluates the items emitted by the source Observable, rather than a second Observable, to terminate the resulting Observable sequence. In this way, it behaves in a similar way to [TakeWhile](takewhile). 

 * Javadoc: [`takeUntil(Func1)` (RxJava 1.1)](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeUntil(rx.functions.Func1))
       ###  RxJS `takeUntil`

     ![takeUntil](http://reactivex.io/documentation/operators/images/takeUntil.png)  RxJS implements the `takeUntil` operator. You can pass it either an Observable or a `Promise` that it will monitor for an item that triggers `takeUntil` to stop mirroring the source Observable. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .takeUntil(Rx.Observable.timer(5000));

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed
```
  `takeUntil` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    There is also a `takeUntilWithTime` operator to which you can pass an absolute time or an initial duration, but this is described on the [Take](take) operator page. 

      ###  RxPHP `takeUntil`

       RxPHP implements this operator as `takeUntil`. 

  Returns the values from the source observable sequence until the other observable sequence produces a value. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/take.php

$observable = Rx\Observable::fromArray([21, 42, 63]);
$observable
    ->take(2)
    ->subscribe($stdoutObserver);
```
  
```
Next value: 21
Next value: 42
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/takeuntil.html>

TakeWhile
=========

 
> mirror items emitted by an Observable until a specified condition becomes false

  ![TakeWhile](http://reactivex.io/documentation/operators/images/takeWhile.c.png)  The TakeWhile mirrors the source Observable until such time as some condition you specify becomes false, at which point TakeWhile stops mirroring the source Observable and terminates its own Observable. 

  #### See Also

 * [Skip](skip)
* [SkipLast](skiplast)
* [SkipUntil](skipuntil)
* [SkipWhile](skipwhile)
* [Take](take)
* [TakeLast](takelast)
* [TakeUntil](takeuntil)
* [Introduction to Rx: SkipWhile and TakeWhile](http://www.introtorx.com/Content/v1.0.10621.0/05_Filtering.html#SkipWhileTakeWhile)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `takeWhile`

     ![takeWhile](http://reactivex.io/documentation/operators/images/takeWhile.png)  The `takeWhile` operator returns an Observable that mirrors the behavior of the source Observable until such time as a function, applied to an item emitted by that Observable, returns `false`, whereupon the new Observable terminates with an `onCompleted` notification. 

 
```
numbers = Observable.from( [1, 2, 3, 4, 5, 6, 7, 8, 9] );

numbers.takeWhile({ ((it < 6) || (0 == (it % 2))) }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
2
3
4
5
6
Sequence complete
```
  `takeWhile` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`takeWhile(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeWhile(rx.functions.Func1))
       ###  RxJava 1․x `takeWhile`

     ![takeWhile](http://reactivex.io/documentation/operators/images/takeWhile.png)  The `takeWhile` operator returns an Observable that mirrors the behavior of the source Observable until such time as a function, applied to an item emitted by that Observable, returns `false`, whereupon the new Observable terminates with an `onCompleted` notification. 


 `takeWhile` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`takeWhile(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#takeWhile(rx.functions.Func1))
       ###  RxJS `takeWhile`

     ![takeWhile](http://reactivex.io/documentation/operators/images/takeWhile.png)  RxJS implements the `takeWhile` operator. You pass it a function that governs the takeping process. `takeWhile` calls that function for each item emitted by the source Observable until such time as the function returns `false`, whereupon `takeWhile` stops mirroring the source Observable (starting with that item) and issues an `onCompleted` notification. The function takes three parameters: 

 1. the emitted item
2. the zero-based index of that item in the sequence of emissions
3. the source Observable

  You may optionally pass a second parameter to `takeWhile`. If so, that item will also be available to your predicate function as “`this`”. 

 #### Sample Code

 
```
var source = Rx.Observable.range(1, 5)
    .takeWhile(function (x) { return x < 3; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 0
Next: 1
Next: 2
Completed
```
  `takeWhile` is found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `takeWhile takeWhileWithIndex`

       RxPHP implements this operator as `takeWhile`. 

  Returns elements from an observable sequence as long as a specified condition is true. It takes as a parameter a a callback to test each source element for a condition. The callback predicate is called with the value of the element. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/takeWhile.php


$source = \Rx\Observable::range(1, 5)
    ->takeWhile(function ($x) {
        return $x < 3;
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Complete!
```
      RxPHP also has an operator `takeWhileWithIndex`. 

  Returns elements from an observable sequence as long as a specified condition is true. It takes as a parameter a a callback to test each source element for a condition. The callback predicate is called with the index and the value of the element. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/takeWhileWithIndex.php


$source = \Rx\Observable::range(1, 5)
    ->takeWhileWithIndex(function ($i) {
        return $i < 3;
    });

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 1
Next value: 2
Next value: 3
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/takewhile.html>

Average
=======

 
> calculates the average of numbers emitted by an Observable and emits this average

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#average)  The Average operator operates on an Observable that emits numbers (or items that can be evaluated as numbers), and emits a single value: the average of all of the numbers emitted by the source Observable. 

  #### See Also

 * [Sum](sum)
* [Introduction to Rx: Min, Max, Sum, and Average](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#MaxAndMin)
* [RxMarbles: `average`](http://rxmarbles.com/#average)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `averageDouble averageFloat averageInteger averageLong`

     In RxGroovy, this operator is not in the ReactiveX core, but is part of the distinct `rxjava-math` module, where it is implemented with four type-specific operators: `averageDouble`, `averageFloat`, `averageInteger`, and `averageLong`. The following example shows how these operators work: 

 #### Sample Code

 
```
def myObservable = Observable.create({ aSubscriber ->
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(4);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(3);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(2);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(1);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onCompleted();
});

Observable.averageInteger(myObservable).subscribe(
  { println(it); },                  // onNext
  { println("Error encountered"); }, // onError
  { println("Sequence complete"); }  // onCompleted
);
```
 
```
2
Sequence complete
```
  ![average](http://reactivex.io/documentation/operators/images/average.f.png)  You can also average not the items themselves but the results of a function applied to each item, as in the illustration above, which emits the average number of sides on the figures emitted by the source Observable. 

   This operator will fail with an `IllegalArgumentException` if the source Observable does not emit any items. 

      ###  RxJava 1․x `averageDouble averageFloat averageInteger averageLong`

     This operator is not in the RxJava core, but is part of the distinct `rxjava-math` module, where it is implemented with four type-specific operators: `averageDouble`, `averageFloat`, `averageInteger`, and `averageLong`. 

  ![average](http://reactivex.io/documentation/operators/images/average.f.png)  You can also average not the items themselves but the results of a function applied to each item, as in the illustration above, which emits the average number of sides on the figures emitted by the source Observable. 

   This operator will fail with an `IllegalArgumentException` if the source Observable does not emit any items. 

      ###  RxJS `average`

     ![average](http://reactivex.io/documentation/operators/images/average.png)  RxJS implements this operator as `average`. The following code sample shows how to use it: 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 9).average();

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 4
Completed
```
   ![average](http://reactivex.io/documentation/operators/images/average.f.png)  You can also average not the items themselves but the results of a function applied to each item, as in the illustration above, which emits the average number of sides on the figures emitted by the source Observable. 

 #### Sample Code

 
```
var arr = [
    { value: 1 },
    { value: 2 },
    { value: 3 }
];

var source = Rx.Observable.fromArray(arr).average(function (x) {
    return x.value;
});

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 2
Completed
```
   `average` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `average`

       RxPHP implements this operator as `average`. 

  Computes the average of an observable sequence of values. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/average/average.php

$source = Rx\Observable::range(0, 9)->average();

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 4
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/average.html>

Concat
======

 
> emit the emissions from two or more Observables without interleaving them

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#concat)  The Concat operator concatenates the output of multiple Observables so that they act like a single Observable, with all of the items emitted by the first Observable being emitted before any of the items emitted by the second Observable (and so forth, if there are more than two). 

   Concat waits to subscribe to each additional Observable that you pass to it until the previous Observable completes. Note that because of this, if you try to concatenate a “hot” Observable, that is, one that begins emitting items immediately and before it is subscribed to, Concat will not see, and therefore will not emit, any items that Observable emits before all previous Observables complete and Concat subscribes to the “hot” Observable. 


 In some ReactiveX implementations there is also a ConcatMap operator (a.k.a. `concat_all`, `concat_map`, `concatMapObserver`, `for`, `forIn`/`for_in`, `mapcat`, `selectConcat`, or `selectConcatObserver`) that transforms the items emitted by a source Observable into corresponding Observables and then concatenates the items emitted by each of these Observables in the order in which they are observed and transformed. 


 The [StartWith](startwith) operator is similar to Concat, but *prepends*, rather than appends, items or emissions of items to those emitted by a source Observable. 


 The [Merge](merge) operator is also similar. It combines the emissions of two or more Observables, but may interleave them, whereas Concat never interleaves the emissions from multiple Observables. 

 #### See Also

 * [Catch](catch)
* [Merge](merge)
* [StartWith](startwith)
* [Introduction to Rx: Concat](http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#Concat)
* [RxMarbles: `concat`](http://rxmarbles.com/#concat)
* [101 Rx Samples: Concat — cold observable](http://rxwiki.wikidot.com/101samples#toc51)
* [101 Rx Samples: Concat — hot observable](http://rxwiki.wikidot.com/101samples#toc52)
* [Loading data from multiple sources with RxJava](http://blog.danlew.net/2015/06/22/loading-data-from-multiple-sources-with-rxjava/) by Dan Lew (example using Concat and First)

 Language-Specific Information
-----------------------------

    ###  RxClojure `concat concat*`

     ![concat](http://reactivex.io/documentation/operators/images/concat.png)  In RxClojure `concat` concatenates some number of individual Observables together in the order in which they are given. 

   ![concat*](http://reactivex.io/documentation/operators/images/concatX.png)  The `concat*` operator concatenates the Observables emitted by an Observable together, in the order in which they are emitted. 

       ###  RxCpp `concat`

     RxCpp implements this operator as `concat`: 

  ![concat](http://reactivex.io/documentation/operators/images/concat.png)       ###  RxGroovy `concat concatWith`

     ![concat](http://reactivex.io/documentation/operators/images/concat.png)  RxGroovy implements this operator as `concat`. There are variants of this operator that take between two and nine Observables as parameters, and that concatenate them in the order they appear in the parameter list. There is also a variant that takes as a parameter an Observable of Observables, and concatenates each of these Observables in the order that they are emitted. 

 #### Sample Code

 
```
odds  = Observable.from([1, 3, 5, 7]);
evens = Observable.from([2, 4, 6]);

Observable.concat(odds, evens).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
1
3
5
7
2
4
6
Sequence complete
```
 * Javadoc: [`concat(Observable<Observable>)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concat(rx.Observable))
* Javadoc: [`concat(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concat(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observables)
   There is also an instance method, `concatWith`, such that `Observable.concat(a,b)` is equivalent to `a.concatWith(b)`. 

 * Javadoc: [`concatWith(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concatWith(rx.Observable))

      ###  RxJava 1․x `concat concatWith`

     ![concat](http://reactivex.io/documentation/operators/images/concat.png)  RxJava implements this operator as `concat`. There are variants of this operator that take between two and nine Observables as parameters, and that concatenate them in the order they appear in the parameter list. There is also a variant that takes as a parameter an Observable of Observables, and concatenates each of these Observables in the order that they are emitted. 

 * Javadoc: [`concat(Observable<Observable>)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concat(rx.Observable))
* Javadoc: [`concat(Observable,Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concat(rx.Observable,%20rx.Observable)) (there are also versions that take up to nine Observables)
   There is also an instance method, `concatWith`, such that `Observable.concat(a,b)` is equivalent to `a.concatWith(b)`. 

 * Javadoc: [`concatWith(Observable)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#concatWith(rx.Observable))

      ###  RxJS `concat concatAll`

     RxJS implements this operator as `concat` and `concatAll`. 

  ![concat](http://reactivex.io/documentation/operators/images/concat.png)  `concat` takes a variable number of Observables (or Promises) as parameters (or a single array of Observables or Promises), and concatenates them in the order they appear in the parameter list (or array). It exists as both an Observable prototype method and as an instance method. 

   ![concatAll](http://reactivex.io/documentation/operators/images/concatAll.png)  `concatAll` is an instance method that operates on an Observable of Observables, concatinating each of these Observables in the order they are emitted. 

   `concat` and `concatAll` are found in each of the following distributions: 

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxKotlin `concat concatWith`

     ![concat](http://reactivex.io/documentation/operators/images/concat.png)  RxKotlin implements this operator as `concat`. There are variants of this operator that take between two and nine Observables as parameters, and that concatenate them in the order they appear in the parameter list. There is also a variant that takes as a parameter an Observable of Observables, and concatenates each of these Observables in the order that they are emitted. 

   There is also an instance method, `concatWith`, such that `Observable.concat(a,b)` is equivalent to `a.concatWith(b)`. 

      ###  RxNET `Concat`

     ![Concat](http://reactivex.io/documentation/operators/images/concat.C.png)  Rx.NET implements this operator as `Concat`. It accepts either an enumerable of Observables, an Observable of Observables, or two Observables as parameters, and concatenates these in the order given. 

       ###  RxPHP `concat concatAll`

       RxPHP implements this operator as `concat`. 

  Concatenate an observable sequence onto the end of the source observable. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/concat/concat.php


$source1 = \Rx\Observable::of(42);
$source2 = \Rx\Observable::of(56);

$source = \Rx\Observable::empty()->concat($source1)->concat($source2);

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 42
Next value: 56
Complete!
```
      RxPHP also has an operator `concatAll`. 

  Concatenates a sequence of observable sequences into a single observable sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/concat/concatAll.php

$source = Rx\Observable::range(0, 3)
    ->map(function ($x) {
        return \Rx\Observable::range($x, 3);
    })
    ->concatAll();

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 0
Next value: 1
Next value: 2
Next value: 1
Next value: 2
Next value: 3
Next value: 2
Next value: 3
Next value: 4
Complete!
```
         ###  RxPY `concat concatAll`

     ![concat](http://reactivex.io/documentation/operators/images/concat.png)  In RxPY `concat` takes a variable number of Observables as parameters (or an array of Observables), and concatenates them in the order they appear in the parameter list (or array). 

   ![concat_all](http://reactivex.io/documentation/operators/images/concat_all.png)  `concatAll` operates on an Observable of Observables, concatinating each of these Observables in the order they are emitted. 

       ###  Rxrb `concat merge_all`

     ![concat](http://reactivex.io/documentation/operators/images/concat.png)  In Rx.rb, the `concat` operator operates on two Observables as an instance operator, or on an array of Observables as a class method. 

   ![merge_all](http://reactivex.io/documentation/operators/images/merge_all.png)  The `merge_all` operator, despite its name, really behaves like a Concat variant in Rx.rb. It accepts an Observable of Observables as its parameter, and concatenates the emissions from these Observables. 

       ###  RxScala `concat ++`

     RxScala implements this operator in two ways. There is a `concat` operator that accepts an Observable of Observables as its parameter, and then concatenates each of these Observables in the order they are emitted. There is also a `++` operator that concatenates one Observable to another. 

  ![plus-plus](http://reactivex.io/documentation/operators/images/plusplus.png)     

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/concat.html>

Count
=====

 
> count the number of items emitted by the source Observable and emit only this value

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#count)  The Count operator transforms an Observable that emits items into an Observable that emits a single value that represents the number of items emitted by the source Observable. 


 If the source Observable terminates with an error, Count will pass this error notification along without emitting an item first. If the source Observable does not terminate at all, Count will neither emit an item nor terminate. 

  #### See Also

 * [Introduction to Rx: Count](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Count)
* [RxMarbles: `count`](http://rxmarbles.com/#count)

 Language-Specific Information
-----------------------------

    ###  RxClojure `count longCount`

     RxClojure has both `count` and `longCount` variants of this operator, but both of these in fact return long values. 

      ###  RxCpp `count`

     RxCpp implements this operator as `count`. 

      ###  RxGroovy `count countLong`

     In RxGroovy the operator is called `count` and the Observable it creates emits an Integer value. There is also a `countLong` whose Observable emits a Long value. 

 #### Sample Code

 
```
def myObservable = Observable.create({ aSubscriber ->
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('Three');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('Two');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext('One');
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onCompleted();
});

myObservable.count().subscribe(
   { println(it); },                          // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence complete"); }          // onCompleted
);
```
 
```
3
Sequence complete
```
 * Javadoc: [`count()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#count())
* Javadoc: [`countLong()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#countLong())

      ###  RxJava 1․x `count countLong`

     In RxJava the operator is called `count` and the Observable it creates emits an Integer value. There is also a `countLong` whose Observable emits a Long value. 

 #### Sample Code

 
```
String[] items = new String[] { "one", "two", "three" };
assertEquals( new Integer(3), Observable.from(items).count().toBlocking().single() );
```
 * Javadoc: [`count()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#count())
* Javadoc: [`countLong()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#countLong())

      ###  RxJS `count`

     In RxJS the operator `count` counts the number of items in the source Observable that satisfy a specified predicate. That predicate takes the form of a function that takes three parameters: 

 1. the emitted item
2. the index of that item in the sequence of emitted items
3. the source Observable

  If the predicate function returns `true`, `count` will increment the tally of items that it will report when the source Observable completes. If you want to count *all* of the items emitted by the source Observable, simply pass `count` a predicate that always returns `true`: 

 #### Sample Code

 
```
numberOfItems = someObservable.count(function() { return true; });
```
  `count` is part of the following packages: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  `count` requires one of any of the following packages: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxKotlin `count`

     RxKotlin implements this operator as `count`. 

 #### Sample Code

 
```
val list = listOf(1, 2, 3, 4, 5)
assertEquals( 5, Observable.from(list)!!.count()!!.toBlocking()!!.single() )
```
      ###  RxNET `Count LongCount`

     In Rx.NET the Observable this operator creates emits an Integer value, but there is also a `LongCount` whose Observable emits a Long value. With both variants, you can either pass the source Observable in to the operator as a parameter or you can call the operator as an instance method of the source Observable (in which case you omit the parameter). 

      ###  RxPHP `count`

       RxPHP implements this operator as `count`. 

  Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/count/count.php

$source = \Rx\Observable::fromArray(range(1, 10));

$subscription = $source->count()->subscribe($stdoutObserver);
```
  
```
Next value: 10
Complete!
```
         ###  RxPY `count`

     In RxPY you have the option to pass `count` a predicate that takes an item emitted by the source Observable as a parameter. If you do so, `count` will emit a count only of those items from the source Observable that the predicate evaluates as `true`. Otherwise, it will emit a count of all items emitted by the source Observable. 

 #### Sample Code

 
```
numberOfItems = someObservable.count()
numberOfNegativeItems = someObservable.count(lambda x: x < 0)
```
      ###  Rxrb `count`

     In Rx.rb you have the option to pass `count` a predicate that takes an item emitted by the source Observable as a parameter. If you do so, `count` will emit a count only of those items from the source Observable that the predicate evaluates as `true`. Otherwise it will emit a count of all items emitted by the source Observable. 

      ###  RxScala `count length longCount size`

     In RxScala the operator `count` counts the number of items in the source Observable that satisfy a specified predicate. That predicate accepts an emitted item as a parameter and returns a Boolean. `count` will emit a count of all items for which this predicate returned `true`. 


 Use `length` or `size` instead if you want to count *all* of the items emitted by the source Observable and emit this count as an Integer, or use `longCount` to emit it as a Long. 

    

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/count.html>

Max
===

 
> emits the item from the source Observable that had the maximum value

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#max)  The Max operator operates on an Observable that emits numbers (or items that can be evaluated as numbers), and emits a single item: the item with the largest number. 

  #### See Also

 * [Min](min)
* [Introduction to Rx: Min, Max, Sum, and Average](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#MaxAndMin)
* [RxMarbles: `max`](http://rxmarbles.com/#max)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `max maxBy`

     In RxGroovy, this operator is not in the ReactiveX core, but is part of the distinct `rxjava-math` module. 

  ![max](http://reactivex.io/documentation/operators/images/max.png)  RxGroovy implements a `max` operator. It takes an optional comparator that it will use instead of its default to compare the value of two items. If more than one item has the identical maximum value, `max` will emit the *last* such item emitted by the source Observable. 

   ![maxBy](http://reactivex.io/documentation/operators/images/maxBy.png)  The `maxBy` operator is similar to `max`, but instead of emitting the item with the maximum value, it emits the item with the maximum *key*, where that key is generated based on a function you provide to `maxBy` 

       ###  RxJava 1․x `max maxBy`

     In RxJava, this operator is not in the ReactiveX core, but is part of the distinct `rxjava-math` module. 

  ![max](http://reactivex.io/documentation/operators/images/max.png)  RxJava implements a `max` operator. It takes an optional comparator that it will use instead of its default to compare the value of two items. If more than one item has the identical maximum value, `max` will emit the *last* such item emitted by the source Observable. 

   ![maxBy](http://reactivex.io/documentation/operators/images/maxBy.png)  The `maxBy` operator is similar to `max`, but instead of emitting the item with the maximum value, it emits the item with the maximum *key*, where that key is generated based on a function you provide to `maxBy` 

       ###  RxJS `max maxBy`

     ![max](http://reactivex.io/documentation/operators/images/max.png)  RxJS implements the `max` operator. It takes an optional comparer function that it will use instead of its default to compare the value of two items.

 #### Sample Code

 
```
var source = Rx.Observable.fromArray([1,3,5,7,9,2,4,6,8]).max();

var subscription = source.subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); } );
```
 
```
Next: 9
Completed
```
   ![maxBy](http://reactivex.io/documentation/operators/images/maxBy.png)  The `maxBy` operator is similar to `max`, but instead of emitting the item with the maximum value, it emits the item with the maximum *key*, where that key is generated based on a function you provide to `maxBy`. `maxBy` also takes an optional second parameter: a comparer function that it will use instead of its default to compare the keys of the two items. 


 `maxBy` emits a list. If more than one item has the maximum key value, each such item will be represented in the list. 

 #### Sample Code

 
```
var source = Rx.Observable.fromArray([1,3,5,7,9,2,4,6,8,9])
               .maxBy( function (x) { return x; } );

var subscription = source.subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); } );
```
 
```
Next: 9,9
Completed
```
   `max` and `maxBy` are found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  They requires one of the following: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `max`

       RxPHP implements this operator as `max`. 

  Returns the maximum value in an observable sequence according to the specified comparer. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/max/max.php

/* Without comparer */
$source = \Rx\Observable::fromArray([1, 3, 5, 7, 9, 2, 4, 6, 8])
    ->max();

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 9
Complete!
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/max/max-with-comparer.php

/* With a comparer */
$comparer = function ($x, $y) {
    if ($x > $y) {
        return 1;
    } elseif ($x < $y) {
        return -1;
    }
    return 0;
};

$source = \Rx\Observable::fromArray([1, 3, 5, 7, 9, 2, 4, 6, 8])
    ->max($comparer);

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 9
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/max.html>

Min
===

 
> emits the item from the source Observable that had the minimum value

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#min)  The Min operator operates on an Observable that emits numbers (or items that can be evaluated as numbers), and emits a single item: the item with the smallest number. 

  #### See Also

 * [Min](min)
* [Introduction to Rx: Min, Max, Sum, and Average](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#MaxAndMin)
* [RxMarbles: `min`](http://rxmarbles.com/#min)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `min minBy`

     In RxGroovy, this operator is not in the ReactiveX core, but is part of the distinct `rxjava-math` module. 

  ![min](http://reactivex.io/documentation/operators/images/min.png)  RxGroovy implements a `min` operator. It takes an optional comparator that it will use instead of its default to compare the value of two items. If more than one item has the identical minimum value, `min` will emit the *last* such item emitted by the source Observable. 

   ![minBy](http://reactivex.io/documentation/operators/images/minBy.png)  The `minBy` operator is similar to `min`, but instead of emitting the item with the minimum value, it emits the item with the minimum *key*, where that key is generated based on a function you provide to `minBy` 

       ###  RxJava 1․x `min minBy`

     In RxJava, this operator is not in the ReactiveX core, but is part of the distinct `rxjava-math` module. 

  ![min](http://reactivex.io/documentation/operators/images/min.png)  RxJava implements a `min` operator. It takes an optional comparator that it will use instead of its default to compare the value of two items. If more than one item has the identical minimum value, `min` will emit the *last* such item emitted by the source Observable. 

   ![minBy](http://reactivex.io/documentation/operators/images/minBy.png)  The `minBy` operator is similar to `min`, but instead of emitting the item with the minimum value, it emits the item with the minimum *key*, where that key is generated based on a function you provide to `minBy` 

       ###  RxJS `min minBy`

     ![min](http://reactivex.io/documentation/operators/images/min.png)  RxJS implements the `min` operator. It takes an optional comparer function that it will use instead of its default to compare the value of two items.

 #### Sample Code

 
```
var source = Rx.Observable.fromArray([1,3,5,7,9,2,4,6,8]).min();

var subscription = source.subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); } );
```
 
```
Next: 1
Completed
```
   ![minBy](http://reactivex.io/documentation/operators/images/minBy.png)  The `minBy` operator is similar to `min`, but instead of emitting the item with the minimum value, it emits the item with the minimum *key*, where that key is generated based on a function you provide to `minBy`. `minBy` also takes an optional second parameter: a comparer function that it will use instead of its default to compare the keys of the two items. 


 `minBy` emits a list. If more than one item has the minimum key value, each such item will be represented in the list. 

 #### Sample Code

 
```
var source = Rx.Observable.fromArray([1,3,5,7,9,2,4,6,8,1])
               .minBy( function (x) { return x; } );

var subscription = source.subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); } );
```
 
```
Next: 1,1
Completed
```
   `min` and `minBy` are found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  They requires one of the following: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `min`

       RxPHP implements this operator as `min`. 

  Returns the minimum value in an observable sequence according to the specified comparer. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/min/min.php

/* Without comparer */
$source = \Rx\Observable::fromArray([1, 3, 5, 7, 9, 2, 4, 6, 8])
    ->min();

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 1
Complete!
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/min/min-with-comparer.php

/* With a comparer */
$comparer = function ($x, $y) {
    if ($x > $y) {
        return 1;
    } elseif ($x < $y) {
        return -1;
    }
    return 0;
};

$source = \Rx\Observable::fromArray([1, 3, 5, 7, 9, 2, 4, 6, 8])
    ->min($comparer);

$subscription = $source->subscribe($createStdoutObserver());
```
  
```
Next value: 1
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/min.html>

Reduce
======

 
> apply a function to each item emitted by an Observable, sequentially, and emit the final value

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#reduce)  The Reduce operator applies a function to the first item emitted by the source Observable and then feeds the result of the function back into the function along with the second item emitted by the source Observable, continuing this process until the source Observable emits its final item and completes, whereupon the Observable returned from Reduce emits the final value returned from the function. 


 This sort of operation is sometimes called “accumulate,” “aggregate,” “compress,” “fold,” or “inject” in other contexts. 

  #### See Also

 * [Scan](scan)
* [Introduction to Rx: Aggregate](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Aggregate)
* [RxMarbles: `reduce`](http://rxmarbles.com/#reduce)
* [Experimentation with RxJava](http://blog.joanzapata.com/experimentation-with-rx/) by Joan Zapata

 Language-Specific Information
-----------------------------

    ###  RxGroovy `collect reduce`

     ![reduce](http://reactivex.io/documentation/operators/images/reduce.png)  The `reduce` operator returns an Observable that applies a function of your choosing to the first item emitted by a source Observable, then feeds the result of that function along with the second item emitted by the source Observable into the same function, then feeds the result of that function along with the third item into the same function, and so on until all items have been emitted by the source Observable. Then it emits the final result from the final call to your function as the sole output from the returned Observable. 


 Note that if the source Observable does not emit any items, `reduce` will fail with an `IllegalArgumentException`. 


 For example, the following code uses `reduce` to compute, and then emit as an Observable, the sum of the numbers emitted by the source Observable: 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5]);

numbers.reduce({ a, b -> a+b }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
15
Sequence complete
```
  `reduce` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`reduce(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#reduce(rx.functions.Func2))
   ![reduce](http://reactivex.io/documentation/operators/images/reduceSeed.png)  There is also a version of `reduce` to which you can pass a seed item in addition to an accumulator function. Note that passing a `null` seed is not the same as not passing a seed. The behavior will be different. If you pass a seed of `null`, you will be seeding your reduction with the item `null`. Note also that if you do pass in a seed, and the source Observable emits no items, reduce will emit the seed and complete normally without error. 


 `reduce` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`reduce(R,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#reduce(R,%20rx.functions.Func2))
   It is a bad idea to use `reduce` to collect emitted items into a mutable data structure. Instead, use `collect` for that purpose. 

  ![collect](http://reactivex.io/documentation/operators/images/collect.png)  The `collect` operator is similar to `reduce` but is specialized for the purpose of collecting the whole set of items emitted by the source Observable into a single mutable data structure to be emitted by the resulting Observable. Pass it two parameters: 

 1. a function that returns the mutable data structure
2. a function that, when given the data structure and an item emitted by the source Observable, modifies the data structure appropriately

  `collect` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`collect(Func0,Action2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#collect(rx.functions.Func0,%20rx.functions.Action2))
       ###  RxJava 1․x `collect reduce`

     ![reduce](http://reactivex.io/documentation/operators/images/reduce.png)  The `reduce` operator returns an Observable that applies a function of your choosing to the first item emitted by a source Observable, then feeds the result of that function along with the second item emitted by the source Observable into the same function, then feeds the result of that function along with the third item into the same function, and so on until all items have been emitted by the source Observable. Then it emits the final result from the final call to your function as the sole output from the returned Observable. 


 Note that if the source Observable does not emit any items, `reduce` will fail with an `IllegalArgumentException`. 


 `reduce` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`reduce(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#reduce(rx.functions.Func2))
   ![reduce](http://reactivex.io/documentation/operators/images/reduceSeed.png)  There is also a version of `reduce` to which you can pass a seed item in addition to an accumulator function. Note that passing a `null` seed is not the same as not passing a seed. The behavior will be different. If you pass a seed of `null`, you will be seeding your reduction with the item `null`. Note also that if you do pass in a seed, and the source Observable emits no items, reduce will emit the seed and complete normally without error. 


 `reduce` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`reduce(R,Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#reduce(R,%20rx.functions.Func2))
   It is a bad idea to use `reduce` to collect emitted items into a mutable data structure. Instead, use `collect` for that purpose. 

  ![collect](http://reactivex.io/documentation/operators/images/collect.png)  The `collect` operator is similar to `reduce` but is specialized for the purpose of collecting the whole set of items emitted by the source Observable into a single mutable data structure to be emitted by the resulting Observable. Pass it two parameters: 

 1. a function that returns the mutable data structure
2. a function that, when given the data structure and an item emitted by the source Observable, modifies the data structure appropriately

  `collect` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`collect(Func0,Action2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#collect(rx.functions.Func0,%20rx.functions.Action2))
       ###  RxJS `reduce`

     ![reduce](http://reactivex.io/documentation/operators/images/reduceSeed.png)  RxJS implements the `reduce` operator. Pass it an accumulator function, and, optionally, a seed value to pass into the accumulator function with the first item emitted by the source Observable. 

 #### Sample Code

 
```
var source = Rx.Observable.range(1, 3)
    .reduce(function (acc, x) {
        return acc * x;
    }, 1)

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: 6
Completed
```
 `reduce` is found in each of the following distributions:

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

 `reduce` requires one of the following distributions:

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

        ###  RxPHP `reduce`

       RxPHP implements this operator as `reduce`. 

  Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/reduce/reduce.php

//Without a seed
$source = \Rx\Observable::fromArray(range(1, 3));

$subscription = $source
    ->reduce(function ($acc, $x) {
        return $acc + $x;
    })
    ->subscribe($createStdoutObserver());
```
  
```
Next value: 6
Complete!
```
  
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/reduce/reduce-with-seed.php

//With a seed
$source = \Rx\Observable::fromArray(range(1, 3));

$subscription = $source
    ->reduce(function ($acc, $x) {
        return $acc * $x;
    }, 1)
    ->subscribe($createStdoutObserver());
```
  
```
Next value: 6
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/reduce.html>

Sum
===

 
> calculates the sum of numbers emitted by an Observable and emits this sum

  [Open interactive diagram on rxmarbles.com](https://rxmarbles.com/#sum)  The Sum operator operates on an Observable that emits numbers (or items that can be evaluated as numbers), and emits a single value: the sum of all of the numbers emitted by the source Observable. 

  #### See Also

 * [Average](average)
* [Introduction to Rx: Min, Max, Sum, and Average](http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#MaxAndMin)
* [RxMarbles: `sum`](http://rxmarbles.com/#sum)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `sumDouble sumFloat sumInteger sumLong StringObservable.join StringObservable.stringConcat`

     In RxGroovy, this operator is not in the ReactiveX core, but is part of the distinct `rxjava-math` module, where it is implemented with four type-specific operators: `sumDouble`, `sumFloat`, `sumInteger`, and `sumLong`. The following example shows how these operators work: 

 #### Sample Code

 
```
def myObservable = Observable.create({ aSubscriber ->
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(4);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(3);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(2);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onNext(1);
  if(false == aSubscriber.isUnsubscribed()) aSubscriber.onCompleted();
});

Observable.sumInteger(myObservable).subscribe(
  { println(it); },                  // onNext
  { println("Error encountered"); }, // onError
  { println("Sequence complete"); }  // onCompleted
);
```
 
```
10
Sequence complete
```
  ![sum](http://reactivex.io/documentation/operators/images/sum.f.png)  You can also sum not the items themselves but the results of a function applied to each item, as in the illustration above, which emits the sum of the number of sides on the figures emitted by the source Observable. 

   ![stringConcat](http://reactivex.io/documentation/operators/images/St.stringConcat.png)  In the distinct `StringObservable` class (not part of RxGroovy by default) there is also a `stringConcat` operator that converts an Observable that emits a sequence of strings into an Observable that emits a single string that represents the concatenation of them all. 

   ![join](http://reactivex.io/documentation/operators/images/St.join.png)  In the distinct `StringObservable` class (not part of RxGroovy by default) there is also a `join` operator that converts an Observable that emits a sequence of strings into an Observable that emits a single string that represents the concatenation of each of them, delimited by a string of your choosing. 

       ###  RxJava 1․x `sumDouble sumFloat sumInteger sumLong StringObservable.join StringObservable.stringConcat`

     This operator is not in the RxJava core, but is part of the distinct `rxjava-math` module, where it is implemented with four type-specific operators: `sumDouble`, `sumFloat`, `sumInteger`, and `sumLong`. 

  ![sum](http://reactivex.io/documentation/operators/images/sum.f.png)  You can also sum not the items themselves but the results of a function applied to each item, as in the illustration above, which emits the sum of the number of sides on the figures emitted by the source Observable. 

   ![stringConcat](http://reactivex.io/documentation/operators/images/St.stringConcat.png)  In the distinct `StringObservable` class (not part of RxJava by default) there is also a `stringConcat` operator that converts an Observable that emits a sequence of strings into an Observable that emits a single string that represents the concatenation of them all. 

   ![join](http://reactivex.io/documentation/operators/images/St.join.png)  In the distinct `StringObservable` class (not part of RxJava by default) there is also a `join` operator that converts an Observable that emits a sequence of strings into an Observable that emits a single string that represents the concatenation of each of them, delimited by a string of your choosing. 

       ###  RxJS `sum`

     ![sum](http://reactivex.io/documentation/operators/images/sum.png)  RxJS implements this operator as `sum`. The following code sample shows how to use it: 

 #### Sample Code

 
```
var source = Rx.Observable.range(0, 9).sum();

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 45
Completed
```
   ![sum](http://reactivex.io/documentation/operators/images/sum.f.png)  You can also sum not the items themselves but the results of a function applied to each item, as in the illustration above, which emits the sum number of sides on the figures emitted by the source Observable. 

 #### Sample Code

 
```
var arr = [
    { value: 1 },
    { value: 2 },
    { value: 3 }
];

var source = Rx.Observable.fromArray(arr).sum(function (x) {
    return x.value;
});

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
```
 
```
Next: 6
Completed
```
   `sum` is found in the following distributions: 

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

  It requires one of the following: 

 * `rx.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

      ###  RxPHP `sum`

       RxPHP implements this operator as `sum`. 

  Computes the sum of a sequence of values 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/sum/sum.php

$source = Rx\Observable::range(1, 10)
    ->sum();

$subscription = $source->subscribe($stdoutObserver);
```
  
```
Next value: 55
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/sum.html>

To
==

 
> convert an Observable into another object or data structure

  ![To](http://reactivex.io/documentation/operators/images/to.c.png)  The various language-specific implementations of ReactiveX have a variety of operators that you can use to convert an Observable, or a sequence of items emitted by an Observable, into another variety of object or data structure. Some of these block until the Observable terminates and then produce an equivalent object or data structure; others return an Observable that emits such an object or data structure. 

   In some implementations of ReactiveX, there is also an operator that converts an Observable into a “Blocking” Observable. A Blocking Observable extends the ordinary Observable by providing a set of methods, operating on the items emitted by the Observable, that block. Some of the To operators are in this Blocking Observable set of extended operations. 

 #### See Also

 * [Introduction to Rx: Leaving the monad](http://www.introtorx.com/Content/v1.0.10621.0/10_LeavingTheMonad.html#LeavingTheMonad)

 Language-Specific Information
-----------------------------

    ###  RxGroovy `BlockingObservable.from BlockingObservable.getIterator nest toBlocking BlockingObservable.toFuture BlockingObservable.toIterable toList toMap toMultiMap toSortedList`

     ![getIterator](http://reactivex.io/documentation/operators/images/B.getIterator.png)  The `getIterator` operator applies to the `BlockingObservable` subclass, so in order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 This operator converts an Observable into an `Iterator` with which you can iterate over the set of items emitted by the source Observable. 

 * Javadoc: [`BlockingObservable.getIterator()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#getIterator())
   ![toFuture](http://reactivex.io/documentation/operators/images/B.toFuture.png)  The `toFuture` operator applies to the `BlockingObservable` subclass, so in order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 This operator converts an Observable into an `Future` that will return the single item emitted by the source Observable. If the source Observable emits more than one item, the `Future` will receive an `IllegalArgumentException`; if it completes after emitting no items, the `Future` will receive a `NoSuchElementException`. 


 If you want to convert an Observable that may emit multiple items into a `Future`, try something like this: `myObservable.toList().toBlocking().toFuture()`. 

 * Javadoc: [`BlockingObservable.toFuture()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#toFuture())
   ![toIterable](http://reactivex.io/documentation/operators/images/B.toIterable.png)  The `toIterable` operator applies to the `BlockingObservable` subclass, so in order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 This operator converts an Observable into an `Iterable` with which you can iterate over the set of items emitted by the source Observable. 

 * Javadoc: [`BlockingObservable.toIterable()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#toIterable())
   ![toList](http://reactivex.io/documentation/operators/images/toList.png)  Normally, an Observable that emits multiple items will do so by invoking its observer’s `onNext` method for each such item. You can change this behavior, instructing the Observable to compose a list of these multiple items and then to invoke the observer’s `onNext` method only once, passing it the entire list, by applying the `toList` operator to the Observable. 


 For example, the following rather pointless code takes a list of integers, converts it into an Observable, then converts that Observable into one that emits the original list as a single item: 

 #### Sample Code

 
```
numbers = Observable.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);

numbers.toList().subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sequence complete
```
  If the source Observable invokes `onCompleted` before emitting any items, the Observable returned by `toList` will emit an empty list before invoking `onCompleted`. If the source Observable invokes `onError`, the Observable returned by `toList` will immediately invoke the `onError` methods of its observers. 


 `toList` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toList()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toList())
   ![toMap](http://reactivex.io/documentation/operators/images/toMap.png)  The `toMap` operator collects the items emitted by the source Observable into a map (by default, a `HashMap`, but you can optionally supply a factory function that generates another `Map` variety) and then emits that map. You supply a function that generates the key for each emitted item. You may also optionally supply a function that converts an emitted item into the value to be stored in the map (by default, the item itself is this value). 


 `toMap` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMap(rx.functions.Func1))
* Javadoc: [`toMap(Func1,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMap(rx.functions.Func1,%20rx.functions.Func1))
* Javadoc: [`toMap(Func1,Func1,Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0))
   ![toMultiMap](http://reactivex.io/documentation/operators/images/toMultiMap.png)  The `toMultiMap` operator is similar to `toMap` except that the map it generates is also an `ArrayList` (by default; or you can pass an optional factory method as a fourth parameter by which you generate the variety of collection you prefer). 


 `toMultiMap` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toMultiMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1))
* Javadoc: [`toMultiMap(Func1,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1,%20rx.functions.Func1))
* Javadoc: [`toMultiMap(Func1,Func1,Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0))
* Javadoc: [`toMultiMap(Func1,Func1,Func0,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0,%20rx.functions.Func1))
   ![toSortedList](http://reactivex.io/documentation/operators/images/toSortedList.png)  The `toSortedList` operator behaves much like `toList` except that it sorts the resulting list. By default it sorts the list naturally in ascending order by means of the `Comparable` interface. If any of the items emitted by the Observable does not support `Comparable` with respect to the type of every other item emitted by the Observable, `toSortedList` will throw an exception. However, you can change this default behavior by also passing in to `toSortedList` a function that takes as its parameters two items and returns a number; `toSortedList` will then use that function instead of `Comparable` to sort the items. 


 For example, the following code takes a list of unsorted integers, converts it into an Observable, then converts that Observable into one that emits the original list in sorted form as a single item: 

 #### Sample Code

 
```
numbers = Observable.from([8, 6, 4, 2, 1, 3, 5, 7, 9]);

numbers.toSortedList().subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sequence complete
```
  Here is an example that provides its own sorting function: in this case, one that sorts numbers according to how close they are to the number 5. 

 
```
numbers = Observable.from([8, 6, 4, 2, 1, 3, 5, 7, 9]);

numbers.toSortedList({ n, m -> Math.abs(5-n) - Math.abs(5-m) }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
```
 
```
[5, 6, 4, 3, 7, 8, 2, 1, 9]
Sequence complete
```
  `toSortedList` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toSortedList()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toSortedList())
* Javadoc: [`toSortedList(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toSortedList(rx.functions.Func2))
   ![nest](http://reactivex.io/documentation/operators/images/nest.png)  RxGroovy also has a `nest` operator that has one particular purpose: it converts a source Observable into an Observable that emits that source Observable as its sole item. 

       ###  RxJava 1․x `BlockingObservable.from BlockingObservable.getIterator nest toBlocking BlockingObservable.toFuture BlockingObservable.toIterable toList toMap toMultiMap toSortedList`

     ![getIterator](http://reactivex.io/documentation/operators/images/B.getIterator.png)  The `getIterator` operator applies to the `BlockingObservable` subclass, so in order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 This operator converts an Observable into an `Iterator` with which you can iterate over the set of items emitted by the source Observable. 

 * Javadoc: [`BlockingObservable.getIterator()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#getIterator())
   ![toFuture](http://reactivex.io/documentation/operators/images/B.toFuture.png)  The `toFuture` operator applies to the `BlockingObservable` subclass, so in order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 This operator converts an Observable into an `Future` that will return the single item emitted by the source Observable. If the source Observable emits more than one item, the `Future` will receive an `IllegalArgumentException`; if it completes after emitting no items, the `Future` will receive a `NoSuchElementException`. 


 If you want to convert an Observable that may emit multiple items into a `Future`, try something like this: `myObservable.toList().toBlocking().toFuture()`. 

 * Javadoc: [`BlockingObservable.toFuture()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#toFuture())
   ![toIterable](http://reactivex.io/documentation/operators/images/B.toIterable.png)  The `toIterable` operator applies to the `BlockingObservable` subclass, so in order to use it, you must first convert your source Observable into a `BlockingObservable` by means of either the `BlockingObservable.from` method or the `Observable.toBlocking` operator. 


 This operator converts an Observable into an `Iterable` with which you can iterate over the set of items emitted by the source Observable. 

 * Javadoc: [`BlockingObservable.toIterable()`](http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html#toIterable())
   ![toList](http://reactivex.io/documentation/operators/images/toList.png)  Normally, an Observable that emits multiple items will do so by invoking its observer’s `onNext` method for each such item. You can change this behavior, instructing the Observable to compose a list of these multiple items and then to invoke the observer’s `onNext` method only once, passing it the entire list, by applying the `toList` operator to the Observable. 


 If the source Observable invokes `onCompleted` before emitting any items, the Observable returned by `toList` will emit an empty list before invoking `onCompleted`. If the source Observable invokes `onError`, the Observable returned by `toList` will immediately invoke the `onError` methods of its observers. 


 `toList` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toList()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toList())
   ![toMap](http://reactivex.io/documentation/operators/images/toMap.png)  The `toMap` operator collects the items emitted by the source Observable into a map (by default, a `HashMap`, but you can optionally supply a factory function that generates another `Map` variety) and then emits that map. You supply a function that generates the key for each emitted item. You may also optionally supply a function that converts an emitted item into the value to be stored in the map (by default, the item itself is this value). 


 `toMap` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMap(rx.functions.Func1))
* Javadoc: [`toMap(Func1,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMap(rx.functions.Func1,%20rx.functions.Func1))
* Javadoc: [`toMap(Func1,Func1,Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0))
   ![toMultiMap](http://reactivex.io/documentation/operators/images/toMultiMap.png)  The `toMultiMap` operator is similar to `toMap` except that the map it generates is also an `ArrayList` (by default; or you can pass an optional factory method as a fourth parameter by which you generate the variety of collection you prefer). 


 `toMultiMap` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toMultiMap(Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1))
* Javadoc: [`toMultiMap(Func1,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1,%20rx.functions.Func1))
* Javadoc: [`toMultiMap(Func1,Func1,Func0)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0))
* Javadoc: [`toMultiMap(Func1,Func1,Func0,Func1)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toMultimap(rx.functions.Func1,%20rx.functions.Func1,%20rx.functions.Func0,%20rx.functions.Func1))
   ![toSortedList](http://reactivex.io/documentation/operators/images/toSortedList.png)  The `toSortedList` operator behaves much like `toList` except that it sorts the resulting list. By default it sorts the list naturally in ascending order by means of the `Comparable` interface. If any of the items emitted by the Observable does not support `Comparable` with respect to the type of every other item emitted by the Observable, `toSortedList` will throw an exception. However, you can change this default behavior by also passing in to `toSortedList` a function that takes as its parameters two items and returns a number; `toSortedList` will then use that function instead of `Comparable` to sort the items. 


 `toSortedList` does not by default operate on any particular [Scheduler](../scheduler). 

 * Javadoc: [`toSortedList()`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toSortedList())
* Javadoc: [`toSortedList(Func2)`](http://reactivex.io/RxJava/javadoc/rx/Observable.html#toSortedList(rx.functions.Func2))
   ![nest](http://reactivex.io/documentation/operators/images/nest.png)  RxJava also has a `nest` operator that has one particular purpose: it converts a source Observable into an Observable that emits that source Observable as its sole item. 

       ###  RxJS `toArray toMap toSet`

     ![toArray](http://reactivex.io/documentation/operators/images/toArray.png)  Normally, an Observable that emits multiple items will do so by invoking its observer’s `onNext` method for each such item. You can change this behavior, instructing the Observable to compose an array of these multiple items and then to invoke the observer’s `onNext` method only once, passing it the entire array, by applying the `toArray` operator to the Observable. 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .take(5)
    .toArray();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: [0,1,2,3,4]
Completed
```
 `toArray` is found in each of the following distributions:

 * `rx.js`
* `rx.all.js`
* `rx.all.compat.js`
* `rx.compat.js`
* `rx.lite.js`
* `rx.lite.compat.js`

    ![toMap](http://reactivex.io/documentation/operators/images/toMap.png)  The `toMap` operator collects the items emitted by the source Observable into a `Map` and then emits that map. You supply a function that generates the key for each emitted item. You may also optionally supply a function that converts an emitted item into the value to be stored in the map (by default, the item itself is this value). 

 #### Sample Code

 
```
var source = Rx.Observable.timer(0, 1000)
    .take(5)
    .toMap(function (x) { return x * 2; }, function (x) { return x * 4; });

var subscription = source.subscribe(
    function (x) {
        var arr = [];
        x.forEach(function (value, key) { arr.push(value, key); })
        console.log('Next: ' + arr);
    },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: [0,0,2,4,4,8,6,12,8,16]
Completed
```
 `toMap` is found in each of the following distributions:

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

    ![toSet](http://reactivex.io/documentation/operators/images/toSet.png)  Normally, an Observable that emits multiple items will do so by invoking its observer’s `onNext` method for each such item. You can change this behavior, instructing the Observable to compose a `Set` of these multiple items and then to invoke the observer’s `onNext` method only once, passing it the entire `Set`, by applying the `toSet` operator to the Observable. 


 Note that this only works in an ES6 environment or polyfilled. 

 
```
var source = Rx.Observable.timer(0, 1000)
    .take(5)
    .toSet();

var subscription = source.subscribe(
    function (x) {
        var arr = [];
        x.forEach(function (i) { arr.push(i); })
        console.log('Next: ' + arr);
    },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
```
 
```
Next: [0,1,2,3,4]
Completed
```
 `toSet` is found in each of the following distributions:

 * `rx.all.js`
* `rx.all.compat.js`
* `rx.aggregates.js`

        ###  RxPHP `toArray`

       RxPHP implements this operator as `toArray`. 

  Creates an observable sequence containing a single element which is an array containing all the elements of the source sequence. 

 #### Sample Code

 
```
//from https://github.com/ReactiveX/RxPHP/blob/master/demo/toArray/toArray.php

$source = \Rx\Observable::fromArray([1, 2, 3, 4]);

$observer = $createStdoutObserver();

$subscription = $source->toArray()
    ->subscribe(new CallbackObserver(
        function ($array) use ($observer) {
            $observer->onNext(json_encode($array));
        },
        [$observer, "onError"],
        [$observer, "onCompleted"]
    ));
```
  
```
Next value: [1,2,3,4]
Complete!
```
       

 © ReactiveX contributors  
Licensed under the Apache License 2.0.  

<http://reactivex.io/documentation/operators/to.html>

reactivex