0

Does this look like a reasonable, if verbose, way to make sure that each click does not stack requests to saveOperation?

I'm using RxJS and storing the instance of the subscription in a mutable ref so it persists between renders. Then, if one exists, I cancel it before starting a new one.

const saveSubscription = useRef<Subscription>(); // RxJS Subscription (cancellable fetch)

const handleChange = () => {
  saveSubscription.current?.unsubscribe();
  saveSubscription.current = saveOperation({ ...data }).subscribe();
}

...

<input type="text" onClick={() => handleChange()} ref={fileInput} />
1
  • 1
    Does not look bad, but I'd rather see the button's click events as a stream and then apply switchMap in order to make use that the current observable which handles the request will be unsubscribed if the click stream emits. Commented Mar 16, 2020 at 21:44

1 Answer 1

2

A more reactive way of solving your issue would be the to always have your subscription open and let your pipe control the data flow. One way could be the usage of switchMap.

One asynchronous value that changes over time is your text input. That could be the outer observable that unsubscribes your inner http request and starts a new one:

// Outer text observable that changes via your input
const text$ = new Subject();

// A fake http function to show async http responses
const fakeHttp$ = (text: string) => of('Http answer: ' + text).pipe(delay(1000));

// The http response that can be subscribed to, cancels the fakeHttp request if a new text$ emits within the old open request
const source$ = text$.pipe(
  switchMap(fakeHttp$)
);

// Your handle change function that can be called in the JSX Input
handleChange = (text: string) => text$.next(text);

Running stackblitz

Sign up to request clarification or add additional context in comments.

3 Comments

Actually something like this looks good: stackblitz.com/edit/react-rxjs-hooks
This is the usage of react hooks in combination with rxjs. You can do this but this was not your question initially. You used a subscribe/unsubscribe mechanism to cancel http requests. What this Stackblitz is focusing is how to get the value from the Observable into your view, if I understand this scenario right. I answered you how to once subscribe and control your http cancelation via the pipe.
You understood my question correctly! However, the answer is in isolation; it's helpful to see the solution in context with React. In the StackBlitz code, we simply can replace line 11, scan, with the switchMap to make the inner observable cancel when a new event (like a click) is emitted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.