T
TanStack17mo ago
literary-plum

Using observables as a return value for queryFn

The docs (https://tanstack.com/query/latest/docs/framework/angular/guides/queries) say "A function that returns a promise or observable ..." However, it seems like it's only possible to return a promise, if you return an Observable, the query is interpreted to resolve an observable (synchronously). Is that a mistake in the docs? Is that something that is planned on being supported in the future? What I worry about is that by converting to promise, it is basically going to be impossible to cancel the request, if it becomes irrelevant shortly after sending. This is usually done automatically in angular http client because an unsubscribe to the observable will cancel the browser network request. What is the recommended way to handle this in angular query?
5 Replies
fascinating-indigo
fascinating-indigo17mo ago
Hi, yes returning observables from queryFn is planned. In fact got this working already on my laptop - biggest challenge is getting all the types right. TanStack Query does support cancellation with promises too, here is an example using Angular:
queryFn: async (context) => {
// Cancels the request when component is destroyed before the request finishes
const abort$ = fromEvent(context.signal, 'abort')
return lastValueFrom(
this.#postsService.postById$(this.postId()).pipe(takeUntil(abort$)),
)
},
queryFn: async (context) => {
// Cancels the request when component is destroyed before the request finishes
const abort$ = fromEvent(context.signal, 'abort')
return lastValueFrom(
this.#postsService.postById$(this.postId()).pipe(takeUntil(abort$)),
)
},
fascinating-indigo
fascinating-indigo17mo ago
StackBlitz
Query Basic Example - StackBlitz
Run official live example code for Query Basic, created by Tanstack on StackBlitz
literary-plum
literary-plumOP17mo ago
Oh so today it should be possible to create a function that wrapps an observable and the "context" and returns a promise but still "cancels" the request? And later that will possibly be done automatically when observables are supported?
fascinating-indigo
fascinating-indigo17mo ago
Yes
literary-plum
literary-plumOP17mo ago
Awesome! Thanks

Did you find this page helpful?