Home > Blockchain >  JavaScript: Promises and RxJS - subscribe() same as then()?
JavaScript: Promises and RxJS - subscribe() same as then()?

Time:12-02

Problem


I am currently working on UI and I use React. Inside of the .jsx component, I have everything : HTML (JSX), JavaScript-Logic, and API calls. Everything in one file, this gets messy.

Goal


I would like to outsource functionality, so I created a class that should handle all API-Calls. I also would like to use RxJS and combine axios with RxJs.

Code


What is happening in the the code? I have a class ApiCalls that contains a static method putApiCallExample. There I do the api call but creating a Promise with axios. I use the from() functionality form rxjs to create an observable and inside the pipe i return the data.

In the Main.jsx I am using this in the useEffect()-hook, I subscribe on it and set the State based on it.

class ApiCalls:
    static putApiCallExample(URL, data){
        const promise = axios
            .put(URL, data, {
                headers: {
                    "Content-Type": "application/json"
                }
            });
    
        return from(promise).pipe(map(res => res.data));
    }


const Main = () => {
    
    const [show, setShow] = useState(false);

    useEffect(() => {
        ApiCalls.putApiCallExample().subscribe(
            res => {
                console.log("1", res);
                setShow(true);
            },
            err => {
                console.log("2", err)
            }

        );
    }, [])

}

Question


  • Can I interpet the subscribe() functionality as same as .then() from axios ?
  • Do I need to unsubscribe here?
  • Does this cause performance issues to mix axios and rxjs?

CodePudding user response:

I assume that if you use Axios, you don't need to receive multiple response from the server like for SSE or websocket. So:

Can I interpet the subscribe() functionality as same as .then() from axios ?

In a way, yes, the observable subscribe callback is triggered when Axios promise resolves. Then it will not be triggered anymore, so in this specific case, the RxJs observable behaves the same way as the Axios promise.

Do I need to unsubscribe here?

As the Observable can't be triggered more than 1 time, I don't see any reason to unsubscribe.

Does this cause performance issues to mix axios and rxjs?

You're only wrap Axios promise into a RxJs observable. This RxJs wrapper will not have a significant memory or CPU blueprint.

By the way, this is basically what's Angular Http client is doing internally. My opinion is that it's safe, but it doesn't bring too much value either.

  • Related