Skip to content

Commit

Permalink
[Cases] Use the default value of observables on the useApplication
Browse files Browse the repository at this point in the history
…hook (elastic#177980)

## Summary

This PR uses the default values of the `currentAppId$` and
`applications$` if they exist.

### For maintainers

- [x] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
  • Loading branch information
cnasikas authored Mar 5, 2024
1 parent b3ab758 commit 6dd9a88
Showing 1 changed file with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,36 @@
* 2.0.
*/
import useObservable from 'react-use/lib/useObservable';
import type { BehaviorSubject, Observable } from 'rxjs';
import { useKibana } from '../../common/lib/kibana';

interface UseApplicationReturn {
appId: string | undefined;
appTitle: string | undefined;
}

const isBehaviorSubjectObservable = <T,>(
observable: Observable<T>
): observable is BehaviorSubject<T> => 'value' in observable;

/**
* Checks if the observable is stateful and, in case, sets up `useObservable` with an initial value
*/
const useStatefulObservable = <T,>(observable: Observable<T>) => {
let initialValue: T | undefined;

if (isBehaviorSubjectObservable(observable)) {
initialValue = observable.value;
}

return useObservable(observable, initialValue);
};

export const useApplication = (): UseApplicationReturn => {
const { currentAppId$, applications$ } = useKibana().services.application;
// retrieve the most recent value from the BehaviorSubject
const appId = useObservable(currentAppId$);
const applications = useObservable(applications$);
const appId = useStatefulObservable(currentAppId$);
const applications = useStatefulObservable(applications$);

const appTitle = appId
? applications?.get(appId)?.category?.label ?? applications?.get(appId)?.title
Expand Down

0 comments on commit 6dd9a88

Please sign in to comment.