Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type Query } from '@tanstack/react-query'
import { of } from 'rxjs'
import { hashKey, type Query } from '@tanstack/react-query'
import { of, type Subscription } from 'rxjs'
import { beforeEach, describe, expect, it } from 'vitest'
import { mock } from 'vitest-mock-extended'

Expand Down Expand Up @@ -31,12 +31,17 @@ describe('observableQueryOptions', () => {
expect(staleTimeValue).toBe(0)
})

it('should set staleTime to Infinity when the query has updated data', () => {
it('should set staleTime to Infinity when the query has an active subscription', () => {
const options = observableQueryOptions({
queryKey,
observableFn: () => of('value'),
})

// Add a subscription to simulate an active query subscription
const mockSubscription = mock<Subscription>()
const queryKeyHash = hashKey(queryKey)
queriesSubscriptions.set(queryKeyHash, mockSubscription)

const staleTimeValue =
typeof options.staleTime === 'function'
? options.staleTime(
Expand Down
11 changes: 9 additions & 2 deletions packages/react-query-observable/src/observableQueryOptions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { type DefaultError, type QueryKey, queryOptions, type UnusedSkipTokenOptions } from '@tanstack/react-query'
import {
type DefaultError,
hashKey,
type QueryKey,
queryOptions,
type UnusedSkipTokenOptions,
} from '@tanstack/react-query'

import { queryFnFromObservableFn } from './queryFn/observableQueryFn'
import { queriesSubscriptions } from './queryFn/queriesWithObservable'
import { type ObservableQueryFunction } from './types'

export interface ObservableQueryOptions<
Expand Down Expand Up @@ -31,7 +38,7 @@ export const observableQueryOptions = <
) =>
queryOptions({
queryFn: queryFnFromObservableFn(options.observableFn),
staleTime: ({ state }) => (state.dataUpdateCount === 0 || state.status === 'error' ? 0 : Infinity),
staleTime: ({ queryKey }) => (queriesSubscriptions.has(hashKey(queryKey)) ? Infinity : 0),
gcTime: 10_000,
...options,
})