|
| 1 | +/** |
| 2 | + * Created by tushar.mathur on 10/10/16. |
| 3 | + */ |
| 4 | + |
| 5 | + |
| 6 | +import {IObservable} from '../types/core/IObservable'; |
| 7 | +import {IObserver} from '../types/core/IObserver'; |
| 8 | +import {IScheduler} from '../types/IScheduler'; |
| 9 | +import {ISubscription} from '../types/core/ISubscription'; |
| 10 | +import {CompositeSubscription} from '../testing/Subscription'; |
| 11 | + |
| 12 | + |
| 13 | +export class JoinValueObserver<T> implements IObserver<T> { |
| 14 | + constructor (private sink: IObserver<T>, private root: JoinObserver<T>) { |
| 15 | + } |
| 16 | + |
| 17 | + next (val: T): void { |
| 18 | + this.sink.next(val) |
| 19 | + } |
| 20 | + |
| 21 | + error (err: Error): void { |
| 22 | + this.sink.error(err) |
| 23 | + } |
| 24 | + |
| 25 | + complete (): void { |
| 26 | + this.root.subscriptionCompleted() |
| 27 | + } |
| 28 | + |
| 29 | +} |
| 30 | + |
| 31 | +export class JoinObserver<T> implements IObserver<IObservable<T>> { |
| 32 | + private count: number; |
| 33 | + private sourceCompleted: boolean; |
| 34 | + |
| 35 | + constructor (private sink: IObserver<T>, private scheduler: IScheduler, private subscriptions: CompositeSubscription) { |
| 36 | + this.sourceCompleted = false |
| 37 | + this.count = 0 |
| 38 | + } |
| 39 | + |
| 40 | + subscriptionCompleted () { |
| 41 | + this.count-- |
| 42 | + this.completeSink() |
| 43 | + } |
| 44 | + |
| 45 | + completeSink () { |
| 46 | + if (this.sourceCompleted && this.count === 0) { |
| 47 | + this.sink.complete() |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + |
| 52 | + next (val: IObservable<T>): void { |
| 53 | + const joinValueObserver = new JoinValueObserver(this.sink, this); |
| 54 | + this.count++ |
| 55 | + this.subscriptions.add( |
| 56 | + val.subscribe(joinValueObserver, this.scheduler) |
| 57 | + ) |
| 58 | + } |
| 59 | + |
| 60 | + error (err: Error): void { |
| 61 | + this.sink.error(err) |
| 62 | + } |
| 63 | + |
| 64 | + complete (): void { |
| 65 | + this.sourceCompleted = true |
| 66 | + this.completeSink() |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | + |
| 71 | +export class JoinObservable<T> implements IObservable<T> { |
| 72 | + constructor (private source: IObservable<IObservable<T>>) { |
| 73 | + } |
| 74 | + |
| 75 | + subscribe (observer: IObserver<T>, scheduler: IScheduler): ISubscription { |
| 76 | + const subscription = new CompositeSubscription() |
| 77 | + subscription.add( |
| 78 | + this.source.subscribe(new JoinObserver(observer, scheduler, subscription), scheduler) |
| 79 | + ) |
| 80 | + return subscription |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +export function join <T> (source: IObservable<IObservable<T>>) { |
| 85 | + return new JoinObservable(source) |
| 86 | +} |
0 commit comments