Skip to content

Commit

Permalink
feat(continueWith): Add continueWith (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
josepot committed Apr 17, 2021
1 parent 145376c commit bf71a05
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
45 changes: 45 additions & 0 deletions source/operators/continueWith-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-etc
*/
/*tslint:disable:no-unused-expression*/

import { of } from "rxjs";
import { marbles } from "rxjs-marbles";
import { continueWith } from "./continueWith";

// prettier-ignore
describe("continueWith", () => {
it(
"should continue with the latest emitted value",
marbles(m => {
const source = m.cold(" abc|");
const expected = " abc(c|)";

const result = source.pipe(continueWith((x) => of(x)));
m.expect(result).toBeObservable(expected);
})
);

it(
"should not continue if the source has not emitted",
marbles(m => {
const source = m.cold(" ---|");
const expected = " ---|";

const result = source.pipe(continueWith((x) => of(x)));
m.expect(result).toBeObservable(expected);
})
);

it(
"should not continue if the mapped observable is EMPTY",
marbles(m => {
const source = m.cold(" abc|");
const expected = " abc|";

const result = source.pipe(continueWith(() => []));
m.expect(result).toBeObservable(expected);
})
);
});
44 changes: 44 additions & 0 deletions source/operators/continueWith.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-etc
*/

import {
from,
Observable,
ObservableInput,
ObservedValueOf,
OperatorFunction,
Subscription,
} from "rxjs";

const NO_VAL: any = {};

export const continueWith = <T, O extends ObservableInput<any>>(
mapper: (value: T) => O
): OperatorFunction<T, T | ObservedValueOf<O>> => (source$) =>
new Observable((observer) => {
let latestValue: T = NO_VAL;
const subscription = new Subscription();

subscription.add(
source$.subscribe({
next: (val) => {
observer.next((latestValue = val));
},
error: (e) => {
observer.error(e);
},
complete: () => {
if (latestValue === NO_VAL) {
observer.complete();
} else {
const nextObservable$ = from(mapper(latestValue));
subscription.add(nextObservable$.subscribe(observer));
}
},
})
);

return subscription;
});

0 comments on commit bf71a05

Please sign in to comment.