RxJS get completed result on subscribe callback - javascript

I am a RxJS beginner, and I want to make my code cleaner.
This is the code I write, I am having problem for receiving completion results.
I want to make my code cleaner, getting result in subscribe callback, without using other Subject to receive result.
Here is my code, rxjs 7.0.1:
import colors from 'colors/safe';
import { Subject } from 'rxjs';
import { throttle } from 'rxjs/operators';
interface IEventTask {
id: string,
createdTime: number
}
let global_counter: number = 0;
const mockHTTPRequest = async (event: IEventTask) => {
return (Promise.resolve().then(async () => {
await new Promise((resolve) => {
global.setTimeout(resolve, 1000);
});
if (event.id === '01') {
throw new Error(`error: ${event.id}`);
}
const result = `result: ${event.id}`;
// I don't know how to get result, so I publish to another Subscriber
subscriber.next(result);
return result;
}))
.catch((error) => {
console.error(error);
})
}
const subject = new Subject<IEventTask>();
subject
.pipe(
throttle(mockHTTPRequest, {
leading: true, trailing: true
})
)
.subscribe({
next: (value) => {
console.log(`${colors.blue(`starting`)} Task#${value.id} at: ${global_counter++}`);
},
error: (error) => {
console.error(error);
},
complete: () => {
// How can I get Promise resolved result here?
console.log(`completed`);
}
});
// It's not the code I want to use, but I don't know how to make it easy.
const subscriber = new Subject<string>();
subscriber.subscribe((result: string) => {
console.log(`${colors.green(`finished`)} ${result} at: ${global_counter++}`);
});
(async () => {
for (let i = 1; i <= 10; i++) {
await new Promise((resolve) => {
global.setTimeout(() => {
resolve(true);
}, 125);
});
const value: IEventTask = {
id: (i).toString().padStart(2, '0'),
createdTime: global_counter++
};
subject.next(value);
}
})();
Thank you very much.

This seems to me like you want to make an HTTP request whenever subject (the variable) gets a new value.
So, you are using throttle with the idea in mind that it should wait for the HTTP request until it is complete and it should provide the returned value. Problem being, that throttle does not provide the latter. (see documentation)
I suggest you use switchMap instead. It expects that the passed function returns an observable and when it emits, then switchMap will forward the value. Furthermore, it completes the inner observable whenever a new value is emitted. Which means that if the HTTP request is not yet completed, it terminates the current request and makes a new one. (see documentation)
import { Subject, Observable, OperatorFunction, pipe, UnaryFunction } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';
const mockHTTPRequest = async (event: IEventTask) => {
return (Promise.resolve().then(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 2000);
});
if (event.id === '01') {
throw new Error(`error: ${event.id}`);
}
const result = `result: ${event.id}`;
// This was needed in order to provide the id in the subscribe section
return {
id: event.id,
result
};
}))
.catch((error) => {
console.error(error);
// This was needed for the filter function to work
return undefined;
})
}
// this filters nullish values: null and undefined
function filterNullish<T>(): UnaryFunction<Observable<T | null | undefined>, Observable<T>> {
return pipe(
filter(x => x != null) as OperatorFunction<T | null | undefined, T>
);
}
const subject = new Subject<IEventTask>();
subject
.pipe(
switchMap(mockHTTPRequest),
filterNullish()
)
.subscribe({
next: (value) => {
console.log(`starting Task#${value.id} at: ${global_counter++}`);
},
error: console.error,
complete: () => {
// How can I get Promise resolved result here?
console.log(`completed`);
}
});
In case that you do not want to cancel a request, but rather get the result of every value passed into subject, then you should use look into this comment: https://stackoverflow.com/a/50809667/12851879
Update:
Here is the entire code with mergeMap (so considering all results regardless of the duration)
import colors from 'colors/safe';
import { Subject, Observable, OperatorFunction, pipe, UnaryFunction } from 'rxjs';
import { filter, mergeMap, tap } from 'rxjs/operators';
interface IEventTask {
id: string,
createdTime: number
}
let global_counter: number = 0;
function waitFor(time: number) {
return new Promise((resolve) => {
setTimeout(resolve, time);
})
}
function filterNullish<T>(): UnaryFunction<Observable<T | null | undefined>, Observable<T>> {
return pipe(
filter(x => x != null) as OperatorFunction<T | null | undefined, T>
);
}
const mockHTTPRequest = async (event: IEventTask) => {
return (Promise.resolve().then(async () => {
await waitFor(2000);
if (event.id === '01') {
throw new Error(`error: ${event.id}`);
}
return `result: ${event.id}`;
}))
.catch((error) => {
console.error(error);
return undefined;
})
}
const subject = new Subject<IEventTask>();
subject
.pipe(
tap(value => console.log(`${colors.blue(`starting`)} Task#${value.id} at: ${global_counter++}`)),
mergeMap(mockHTTPRequest),
filterNullish()
)
.subscribe({
next: (result) => {
console.log(`${colors.green(`finished`)} ${result} at: ${global_counter++}`);;
},
error: console.error
});
(async () => {
for (let i = 1; i <= 10; i++) {
await waitFor(125);
const value: IEventTask = {
id: (i).toString().padStart(2, '0'),
createdTime: global_counter++
};
subject.next(value);
}
})();

Related

Redux - Asynchronous response from web socket request

I have a websocket interface which I implemented so that I can use to send requests.
The problem is that the response is asynchronous and it initially returns the empty array because retObj is not updated from the callback function that I sent in. How can I make this function so that it will return the populated array when it has been updated.
This is how my Service looks like:
import * as interface from '../webSocket'
const carService = () => {
return {
getCars: () => {
interface.sendRequest(function (returnObject) {
//
}).then(d => d)
}
}
}
export default carService()
And this is how my action looks like:
import { GET_CARS } from '../constants'
import carService from '../carService'
export const getCars = () => async (dispatch) => {
try {
const cars = await carService.getCars()
console.log("At cars actions: ", cars) // logs: Array []
dispatch(getCarsSuccess(cars))
} catch (err) {
console.log('Error: ', err)
}
}
const getCarsSuccess = (cars) => ({
type: GET_CARS,
payload: cars
})
You simply have to wrap your callback into promise, since it was not a promise to begin with, which is why you cannot use then or await
import * as interface from '../webSocket'
const carService = () => {
return {
getCars: () => {
return new Promise(resolve => interface.sendRequest(function (returnObject) {
resolve(returnObject.msg)
}));
}
}
}
export default carService()
The problem is, you cant await a function unless it returns a Promise. So, as you can guess, the problem lies in carService.getCars's definition. Try this:
getCars: () => {
return new Promise((resolve, reject) => {
interface.sendRequest(function(returnObject) {
// if theres an error, reject(error)
resolve(returnObject);
})
})
}
Or, if sendRequest os am async function, simply return the return value of sendRequest:
getCars: () => {
return interface.sendRequest()
}

jest.advanceTimersByTime doesn't work when I try to test my retry util function

I have a retry util function I wanted to test for. It looks like this
export const sleep = (t: number) => new Promise((r) => setTimeout(r, t));
type RetryFn = (
fn: Function,
config: {
retryIntervel: number;
retryTimeout: number;
predicate: Function;
onRetrySuccess?: Function;
onRetryFail?: Function;
}
) => Promise<any>;
export const retry: RetryFn = async (
fn,
{ predicate, onRetrySuccess, onRetryFail, retryIntervel, retryTimeout }
) => {
const startTime = Date.now();
let retryCount = 0;
while (Date.now() - startTime < retryTimeout) {
try {
const ret = await fn();
if (predicate(ret)) {
if (retryCount > 0) onRetrySuccess && onRetrySuccess();
return ret;
} else {
throw new Error();
}
} catch {
retryCount++;
}
await sleep(retryIntervel);
}
if (onRetryFail) onRetryFail();
};
what it does is retry the function for a period of time at a given interval.
I thought I could use jest.advanceTimersByTime to advance the timer to test how many times the retry happens.
import { retry } from "./index";
const value = Symbol("test");
function mockFnFactory(numFailure: number, fn: Function) {
let numCalls = 0;
return function () {
fn();
numCalls++;
if (numCalls <= numFailure) {
console.log("numCalls <= numFailure");
return Promise.resolve({ payload: null });
} else {
console.log("numCalls => numFailure");
return Promise.resolve({
payload: value
});
}
};
}
describe("retry function", () => {
beforeEach(() => {
jest.useFakeTimers();
});
it("retrys function on 1st attempt, and succeed thereafter", async () => {
const fn = jest.fn();
const onRetrySuccessFn = jest.fn();
const mockFn = mockFnFactory(3, fn);
retry(mockFn, {
predicate: (res: any) => res.payload === value,
onRetrySuccess: onRetrySuccessFn,
retryIntervel: 1000,
retryTimeout: 5 * 60 * 1000
});
jest.advanceTimersByTime(1000);
expect(fn).toHaveBeenCalledTimes(1);
expect(onRetrySuccessFn).not.toHaveBeenCalled();
jest.advanceTimersByTime(1000);
expect(fn).toHaveBeenCalledTimes(2); // 🚨 fail
expect(onRetrySuccessFn).not.toHaveBeenCalled();
jest.advanceTimersByTime(2000);
expect(fn).toHaveBeenCalledTimes(3);// 🚨 fail
expect(onRetrySuccessFn).toHaveBeenCalledTimes(1);
});
});
but it seems like no matter how much I advanced the timer, the function only gets invoked once.
You can find the code on codesandbox at https://codesandbox.io/s/lucid-knuth-e810e?file=/src/index.test.ts
However, there is a known issue with codesandbox where it keeps throwing this error TypeError: jest.advanceTimersByTime is not a function . This error doesn't appear locally.
It's because of this.
Here's what I use in a test helpers file:
const tick = () => new Promise(res => setImmediate(res));
export const advanceTimersByTime = async time => jest.advanceTimersByTime(time) && (await tick());
export const runOnlyPendingTimers = async () => jest.runOnlyPendingTimers() && (await tick());
export const runAllTimers = async () => jest.runAllTimers() && (await tick());
In my test file, I import my helpers and instead of calling jest.advanceTimersByTime, I await my advanceTimersByTime function.
In your specific example, you just need to await a function after calling advanceTimersByTime - like this:
// top of your test file
const tick = () => new Promise(res => setImmediate(res));
... the rest of your existing test file
jest.advanceTimersByTime(1000);
expect(fn).toHaveBeenCalledTimes(1);
expect(onRetrySuccessFn).not.toHaveBeenCalled();
jest.advanceTimersByTime(1000);
await tick(); // this line
expect(fn).toHaveBeenCalledTimes(2);
expect(onRetrySuccessFn).not.toHaveBeenCalled();
jest.advanceTimersByTime(2000);
await tick(); // this line
expect(fn).toHaveBeenCalledTimes(3)
expect(onRetrySuccessFn).toHaveBeenCalledTimes(1);
I am a little late but I had to solve this problem today and I solved it by making this new util function.
// So we can wait setTimeout loops
export const advanceTimersByNTimes = (n = 1, time = 1000) => {
for (let i = 0; i < n; i++) {
act(() => {
jest.advanceTimersByTime(time * 1);
});
}
};
and this is how I use this in the test:
await waitFor(() => {
expect(screen.queryByTestId("timeout-exceeded-container")).toBeNull();
});
advanceTimersByNTimes(11);
await waitFor(() => {
expect(screen.queryByTestId("timeout-exceeded-container")).not.toBeNull();
});
Nothing else worked for me, including the answers here.
This is the part in my code that doesn't work without the above hack (for reference):
setTimeout(() => setSeconds((prev) => prev + 1), 1000);
It would step to 2 times no matter what I've set jest.advanceTimersByTime to, those calls need to be wrapped in act blocks to count.

cancel multiple promises inside a promise on unmount?

hi i want to cancel promise on unmount since i received warning,
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
My code:
const makeCancelable = (promise: Promise<void>) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
(val) => (hasCanceled_ ? reject({ isCanceled: true }) : resolve(val)),
(error) => (hasCanceled_ ? reject({ isCanceled: true }) : reject(error))
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
useEffect(() => {
const initialize = async () => {
const getImageFilesystemKey = (remoteUri: string) => {
const [_, fileName] = remoteUri.split('toolbox-talks/');
return `${cacheDirectory}${fileName}`;
};
const filesystemUri = getImageFilesystemKey(uri);
try {
// Use the cached image if it exists
const metadata = await getInfoAsync(filesystemUri);
if (metadata.exists) {
console.log('resolve 1');
setFileUri(filesystemUri);
} else {
const imageObject = await downloadAsync(uri, filesystemUri);
console.log('resolve 2');
setFileUri(imageObject.uri);
}
// otherwise download to cache
} catch (err) {
console.log('error 3');
setFileUri(uri);
}
};
const cancelable = makeCancelable(initialize());
cancelable.promise
.then(() => {
console.log('reslved');
})
.catch((e) => {
console.log('e ', e);
});
return () => {
cancelable.cancel();
};
}, []);
but i still get warning on fast press, help me please?
You're cancelling the promise, but you are not cancelling the axios call or any of the logic that happens after it inside initialize(). So while it is true that the console won't print resolved, setFileUri will be called regardless, which causes your problem.
A solution could look like this (untested):
const makeCancelable = (promise: Promise<void>) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
val => (hasCanceled_ ? reject({ isCanceled: true }) : resolve(val)),
error => (hasCanceled_ ? reject({ isCanceled: true }) : reject(error))
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
}
};
};
const initialize = async () => {
const getImageFilesystemKey = (remoteUri: string) => {
const [_, fileName] = remoteUri.split("toolbox-talks/");
return `${cacheDirectory}${fileName}`;
};
const filesystemUri = getImageFilesystemKey(uri);
try {
// Use the cached image if it exists
const metadata = await getInfoAsync(filesystemUri);
if (metadata.exists) {
console.log("resolve 1");
return filesystemUri;
} else {
const imageObject = await downloadAsync(uri, filesystemUri);
console.log("resolve 2");
return imageObject.uri;
}
// otherwise download to cache
} catch (err) {
console.error("error 3", err);
return uri;
}
};
useEffect(() => {
const cancelable = makeCancelable(initialize());
cancelable.promise.then(
fileURI => {
console.log("resolved");
setFileUri(fileURI);
},
() => {
// Your logic is such that it's only possible to get here if the promise is cancelled
console.log("cancelled");
}
);
return () => {
cancelable.cancel();
};
}, []);
This ensures that you will only call setFileUri if the promise is not cancelled (I did not check the logic of makeCancelable).

Angular 6 : async await some variable got it variable

Under my Angular 6 app, I have a variable "permittedPefs" which is getting value after an HTTP call (asynchronous)
#Injectable()
export class FeaturesLoadPermissionsService {
permittedPefs = [];
constructor() {
this.loadUserPefsService.getUserRolePefs(roleId)
.subscribe(
(returnedListPefs) => {
this.permittedPefs = returnedListPefs;
},
error => {
console.log(error);
});
}
}
in another method, I'm using that same variable:permittedPefs
But as it's initially empty and it gots its value after such a time, so I need to wait for it to re-use it.
I've tried to use async-await, and my purpose is waiting for permittedPefs to got aobject value
async checkPefPresence(pefId) {
const listPefs = await this.permittedPefs
}
how to fix it ??
As loadUserPefsService.getUserRolePefs method returns Observable you can store it and subscribe to it later when you need it.
#Injectable()
export class FeaturesLoadPermissionsService {
permittedPefs = [];
constructor() {
this.userRolePefsObservable = this.loadUserPefsService.getUserRolePefs(roleId);
}
}
checkPefPresence(pefId) {
let listPefs;
this.userRolePefsObservable.subscribe(
(returnedListPefs) => {
listPefs = returnedListPefs;
},
error => {
console.log(error);
});
}
Use a behaviorSubject
#Injectable()
export class FeaturesLoadPermissionsService {
permittedPefs: BehaviorSubject<any[]> = new BehaviorSubject([]);
constructor() {
this.loadUserPefsService.getUserRolePefs(roleId)
.subscribe((returnedListPefs) => {
this.permittedPefs.next(returnedListPefs);
},
error => {
console.log(error);
});
}
}
Then where ever you are checking for it(remember to unsubscribe when you are done)
if it has to be async you can do it like below
async checkPefPresence(pefId): Promise {
return new Promise((resolve, reject) => {
this.featuresLoadPermissionsService.permittedPefs.subscribe(listPefs => {
//handle whatever check you want to do here
resolve();
},reject);
})

Testing Redux Thunk Action Creator

I've got a redux action creator that utilizes redux-thunk to do some logic to determine what to dispatch to the store. Its not promise-based, like an HTTP request would be, so I am having some issues with how to test it properly. Ill need a test for when the value meets the condition and for when it doesn't. Since the action creator does not return a promise, I cannot run a .then() in my test. What is the best way to test something like this?
Likewise, I believe it would be pretty straightforward testing the getRemoveFileMetrics() action creator as it actually does return a promise. But how can I assert that that will called if the value is removeFiles and meets the condition? How can that be written in the test?
Thanks in advance as this has had me stuck for the last couple of days.
Action Creators
export const handleSelection = (value, cacheKey) => {
return dispatch => {
if (value === "removeFiles") {
dispatch(getRemoveFileMetrics(cacheKey));
}
dispatch({ type: HANDLE_SELECTION, value });
};
};
export const getRemoveFileMetrics = cacheKey => {
return dispatch => {
dispatch({ type: IS_FETCHING_DELETE_METRICS });
return axios
.get(`../GetRemoveFileMetrics`, { params: { cacheKey } })
.then(response => {
dispatch({ type: GET_REMOVE_FILE_METRICS, payload: response.data });
})
.catch(err => console.log(err));
};
};
Jest
it("should dispatch HANDLE_SELECTION when selecting operation", () => {
const store = mockStore({});
const value = "switchVersion";
const expectedAction = [{
type: MOA.HANDLE_SELECTION,
value,
}]; // TypeError: Cannot read property 'then' of undefined
return store.dispatch(MOA.handleSelection(value)).then(() => {
const returnedActions = store.getActions();
expect(returnedActions).toEqual(expectedAction);
});
});
NEW EDIT
So based off of Danny Delott's answer to return a promise, I acheived a passing test as follows:
export const handleSelection = (value, cacheKey) => {
return dispatch => {
if (value === "removeFiles") {
return dispatch(getRemoveFileMetrics(cacheKey));
}
return new Promise((resolve, reject) => {
resolve(dispatch({ type: HANDLE_SELECTION, value }));
});
};
};
Is there a reason to explicitly NOT return a promise in your action creator? It looks like getRemoveFileMetrics is returning the promise, it just gets swallowed in handleSelection...
Easiest solution is to just return the promise:
export const handleSelection = (value, cacheKey) => {
return dispatch => {
if (value === "removeFiles") {
return dispatch(getRemoveFileMetrics(cacheKey));
}
dispatch({ type: HANDLE_SELECTION, value });
return new Promise();
};
};
Otherwise, you'll need make your assertions after the event loop is finished. You can do with a setTimeout wrapped in a Promise to get the .then behavior.
it("should dispatch HANDLE_SELECTION when selecting operation", () => {
const store = mockStore({});
const value = "switchVersion";
const expectedAction = [{
type: MOA.HANDLE_SELECTION,
value,
}];
store.dispatch(MOA.handleSelection(value));
// flush outstanding async tasks
return new Promise(resolve => {
setTimeout(resolve, 0);
})
.then(() => {
const returnedActions = store.getActions();
expect(returnedActions).toEqual(expectedAction);
});
});

Categories

Resources