DEV Community

Discussion on: Vanilla JavaScript vs. RxJs

Collapse
 
riccardoodone profile image
Riccardo Odone • Edited

Hello Tobias, let's see if I can help with your questions.

why is there .subscribe?

In RxJs you need to subscribe to the observable to consume the values it produces.

how many responses do you expect?

An observable is a stream of values, it's like an array that grows over-time. For example, fromEvent(element, 'input').subscribe(x => console.log(x)) logs every time the input event is fired by element.

are they so many that they need to get mapped?

Yes, it's a stream of values.

where would you put a breakpoint in the declaritive code?

You can use tap as Felix mentioned.

RxJs is both powerful and complex. It took me a long time to learn the basics, and I still make many mistakes with it. But I believe it's worth learning because it really gives a different perspective.

Collapse
 
bias profile image
Tobias Nickel

thanks, now you have described the api to me. I see, that in this style of code, everything is treated as a stream. However, an api request, a call via fetch, is fundamentally a single in and a single out. there is no stream of responses. The stream will always only have a single response or a single error. that is what async/await is about, and you get nice meaningfull stacktraces for debugging.

Thread Thread
 
riccardoodone profile image
Riccardo Odone • Edited

However, an api request, a call via fetch, is fundamentally a single in and a single out.

It doesn't have to be, it can be a response stream:

// https://web.dev/fetch-upload-streaming/

const response = await fetch(url);
const reader = response.body.getReader();

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  console.log('Received', value);
}

console.log('Response fully received');
Enter fullscreen mode Exit fullscreen mode

However, I agree most of the time it's not used that way. Still, treating everything as a stream has the advantage of making things composable and re-usable.

In any case, I'm not advocating for any approach. I should have made it more clear in the post. Also, you are right, I could have used async/await in the vanilla JavaScript code to make it look cleaner.