Skip to content

Latest commit

 

History

History
98 lines (77 loc) · 3.45 KB

partition.md

File metadata and controls

98 lines (77 loc) · 3.45 KB

Rx.Observable.prototype.partition(predicate, [thisArg])

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.

Arguments

  1. predicate (Function): Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. The callback is called with the following information:
    1. the value of the element
    2. the index of the element
    3. the Observable object being subscribed
  2. [thisArg] (Any): Object to use as this when executing the predicate.

Returns

(Array): An array of observables. The first triggers when the predicate returns true, and the second triggers when the predicate returns false.

Example

An example using ES6 syntax:

let [evens, odds] = Rx.Observable.range(0, 10)
  .partition(x => x % 2 === 0);

let subscription1 = evens.subscribe(
  x  => console.log('Evens: %s', x),
  e  => console.log('Error: %s', e),
  () => console.log('Completed')
);

// => Evens: 0
// => Evens: 2
// => Evens: 4
// => Evens: 6
// => Evens: 8
// => Completed

let subscription2 = odds.subscribe(
  x  => console.log('Odds: %s', x),
  e  => console.log('Error: %s', e),
  () => console.log('Completed')
);

// => Odds: 1
// => Odds: 3
// => Odds: 5
// => Odds: 7
// => Odds: 9
// => Completed

Example

<div id="dom-event-source"></div>
<div id="dom-event-output">
    <div class="left"><p></p></div>
    <div class="right"><p></p></div>
</div>
var sourceElement = document.getElementById("dom-event-source");
var elements = ["#dom-event-output .left p", "#dom-event-output .right p"].map(document.querySelector.bind(document));
var elementRect = sourceElement.getBoundingClientRect();

var observers = Rx.Observable.fromEvent(sourceElement, 'mousemove')
.map(e => ({
      x: Math.floor(e.clientX - elementRect.left), 
      y: Math.floor(e.clientY - elementRect.top)
    })
).partition(pos => pos.x < sourceElement.clientWidth / 2);

elements.forEach((n, i, a) => 
                 observers[i].subscribe(displayCoordinates.bind(displayCoordinates, n)));

function displayCoordinates(element, pos) {
  element.textContent = `(x: ${pos.x}, y: ${pos.y})`;
}

Location

File:

Dist:

NPM Packages:

NuGet Packages:

Unit Tests: