DEV Community

Discussion on: I changed my mind. Angular needs a reactive primitive

Collapse
 
lucaster profile image
lucaster

Some things that take 4 lines of code with RxJS + Angular only take a single character with RxJS + Svelte.

This sounds amazing! Would you provide an example?
Thanks!

Collapse
 
mfp22 profile image
Mike Pearson

Angular

data: Data | undefined;
sub = this.data$.subscribe(data => this.data = data);

onDestroy() {
  this.sub.unsubscribe();
}
Enter fullscreen mode Exit fullscreen mode

Svelte

$: data = $data$;
Enter fullscreen mode Exit fullscreen mode

That little $ prefix is telling Svelte to subscribe and unsubscribe appropriately. It's concise and declarative, but it isn't valid JavaScript; Svelte is a compiler. But it's worth it imo, because Angular's syntax is both verbose and imperative. Subscribing only breaks out of the reactive paradigm if you don't have another reactive paradigm on the other side. Svelte has synchronous reactivity built in.

It even works in callback functions. Here's another example:

Angular

(submit)="saveData()"
Enter fullscreen mode Exit fullscreen mode
saveData() {
  this.data$.pipe(first()).subscribe(
    data => this.service.saveData(data);
  );
}
Enter fullscreen mode Exit fullscreen mode

(Or you could use rxLet and pass up the unwrapped value from the template into the callback function.)

Svelte

on:submit={() => saveData($data$)}
Enter fullscreen mode Exit fullscreen mode

You can play with a Svelte demo I made here

Collapse
 
mfp22 profile image
Mike Pearson

Updated Example with Signals

Angular

data = toSignal(this.data$);
Enter fullscreen mode Exit fullscreen mode

Svelte

$: data = $data$;
Enter fullscreen mode Exit fullscreen mode

Angular Callback

data = toSignal(this.data$);
Enter fullscreen mode Exit fullscreen mode
(submit)="saveData(data())"
Enter fullscreen mode Exit fullscreen mode

Svelte Callback

on:submit={() => saveData($data$)}
Enter fullscreen mode Exit fullscreen mode

Some comments have been hidden by the post's author - find out more