-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
34 lines (28 loc) · 1.07 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import type { Subject } from 'rxjs'
import { BehaviorSubject } from 'rxjs'
import type { Ref } from 'vue-demi'
import { ref, watch } from 'vue-demi'
import { tryOnScopeDispose } from '@vueuse/shared'
import type { UseObservableOptions } from '../useObservable'
export interface UseSubjectOptions<I = undefined> extends Omit<UseObservableOptions<I>, 'initialValue'> {
}
export function useSubject<H>(subject: BehaviorSubject<H>, options?: UseSubjectOptions): Ref<H>
export function useSubject<H>(subject: Subject<H>, options?: UseSubjectOptions): Ref<H | undefined>
export function useSubject<H>(subject: Subject<H>, options?: UseSubjectOptions) {
const value = ref(
subject instanceof BehaviorSubject
? subject.value
: undefined,
) as typeof subject extends BehaviorSubject<H> ? Ref<H> : Ref<H | undefined>
const subscription = subject.subscribe({
next(val) { value.value = val },
error: options?.onError,
})
watch(value, (nextValue) => {
subject.next(nextValue)
})
tryOnScopeDispose(() => {
subscription.unsubscribe()
})
return value
}