When Angular shipped rxResource, a lot of developers, myself included, immediately asked: can I use this for mutations too?
The answer is technically yes. Practically, no.
Here's what it looks like when you try:
private readonly saveTrigger = signal<Payload | undefined>(undefined);
private readonly saveResource = rxResource({
params: () => this.saveTrigger(),
stream: ({ params }) => this.api.save(params)
});
save() {
this.saveTrigger.set(this.buildPayload());
}
Three things go wrong immediately.
First, params starts as undefined. rxResource still evaluates the stream, so on initial render, before the user has done anything, your save API gets called with undefined. You can guard against this, but you're already fighting the primitive.
Second, if the user saves twice with identical data, saveTrigger.set() produces a new object reference each time, so the signal technically changes, and the save fires. But if anything in your pipeline normalises the payload or Angular's scheduler batches the sets, you might skip the second trigger silently.
Third, error recovery is broken. After a failed save, saveTrigger still holds the last payload. The next save() call with the same data produces a new object reference, which re-triggers. That might be what you want. Or it might not. rxResource wasn't designed to give you control over this.
The correct tool for a one-shot mutation is a direct subscribe:
private readonly isSavingSignal = signal(false);
save(): void {
const payload = this.buildPayload();
this.isSavingSignal.set(true);
this.api.save(payload).pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe({
next: response => {
this.handleSuccess(response);
this.isSavingSignal.set(false);
},
error: () => {
this.handleError();
this.isSavingSignal.set(false);
}
});
}
Explicit, predictable, recoverable. isSavingSignal is a plain WritableSignal: readable anywhere, testable in isolation.
The rule I now apply: rxResource is for idempotent reads. If calling the operation twice with the same input would be a problem, it's a command, and commands don't belong in rxResource.
RxJS and Signals aren't competing. They're for different jobs. The skill is knowing which job you're solving before you pick the tool.
Originally published on ysndmr.com.
Top comments (0)