Skip to content

Commit b141e54

Browse files
authored
Merge pull request #64 from PrefectHQ/subscriptions-with-dependencies
Feature: useSubscriptionWithDependencies
2 parents a41f14f + 42e5658 commit b141e54

File tree

3 files changed

+38
-3
lines changed

3 files changed

+38
-3
lines changed

src/useSubscription/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from './utilities'
22
export * from './models'
33
export * from './types'
4-
export * from './useSubscription'
4+
export * from './useSubscription'
5+
export * from './useSubscriptionWithDependencies'

src/useSubscription/useSubscription.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { getCurrentInstance, onUnmounted, reactive, watch } from 'vue'
1+
import { getCurrentInstance, onUnmounted, reactive, unref, watch } from 'vue'
22
import Manager from './models/manager'
33
import { Action, ActionArguments } from './types/action'
44
import { SubscribeArguments, UseSubscription } from './types/subscription'
@@ -18,7 +18,8 @@ export function useSubscription<T extends Action>(...[action, args, options = {}
1818

1919
if (watchable !== null) {
2020
unwatch = watch(watchable, () => {
21-
if (!subscriptionResponse.isSubscribed()) {
21+
// checking if args are null to support useSubscriptionWithDependencies
22+
if (!subscriptionResponse.isSubscribed() || unref(argsWithDefault) === null) {
2223
unwatch!()
2324
return
2425
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { Ref, watchEffect } from 'vue'
2+
import { Action, SubscriptionOptions, UseSubscription, ActionArguments } from './types'
3+
import { useSubscription } from './useSubscription'
4+
5+
const voidAction = (): undefined => undefined
6+
7+
type UseSubscriptionWithDependencies<T extends Action> = [
8+
action: T,
9+
args: Ref<Parameters<T> | null>,
10+
options?: SubscriptionOptions
11+
]
12+
13+
export function useSubscriptionWithDependencies<T extends Action>(...[action, args, options = {}]: UseSubscriptionWithDependencies<T>): UseSubscription<T | typeof voidAction> {
14+
const subscription = useSubscription(voidAction)
15+
16+
watchEffect(() => {
17+
if (args.value === null) {
18+
if (subscription.isSubscribed()) {
19+
subscription.unsubscribe()
20+
}
21+
22+
Object.assign(subscription, useSubscription(voidAction))
23+
24+
return
25+
}
26+
27+
const newSubscription = useSubscription(action, args as ActionArguments<T>, options)
28+
29+
Object.assign(subscription, newSubscription)
30+
})
31+
32+
return subscription
33+
}

0 commit comments

Comments
 (0)