UNPKG

material-motion

Version:

Makes it easy to add rich, interactive motion to your application.

66 lines 2.75 kB
/** @license * Copyright 2016 - present The Material Motion Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { MotionObservable, } from './observables/proxies'; import { isIterable, isObservable, } from './typeGuards'; export function combineLatest(streams, { waitForAllValues = true } = {}) { return new MotionObservable((observer) => { const outstandingKeys = new Set(Object.keys(streams)); let nextValue; if (isIterable(streams)) { nextValue = []; } else { nextValue = {}; } const subscriptions = {}; let initializing = true; outstandingKeys.forEach(checkKey); initializing = false; // TypeScript doesn't know whether the index signature for `streams` (and // hence, `nextValue` and `outstandingKeys`) is a string or a number. // Thus, it throws an error at a simple `streams[key]`. Since we know // that whichever it is, `key` can index into all three collections, we // cast each to `Dict<V>` and `key` to `string`. Then, TypeScript will // happily index into the collections using `key`. function checkKey(key) { const maybeStream = streams[key]; if (isObservable(maybeStream)) { subscriptions[key] = maybeStream.subscribe((value) => { outstandingKeys.delete(key); nextValue[key] = value; emitNextValue(); }); } else { outstandingKeys.delete(key); nextValue[key] = maybeStream; emitNextValue(); } } function emitNextValue() { if (waitForAllValues ? outstandingKeys.size === 0 : !initializing) { observer.next((Array.isArray(nextValue) ? [...nextValue] : Object.assign({}, nextValue))); } } emitNextValue(); return function disconnect() { Object.values(subscriptions).forEach(subscription => subscription.unsubscribe()); }; }); } //# sourceMappingURL=combineLatest.js.map