Skip to content

Instantly share code, notes, and snippets.

@danguilherme
Created May 21, 2019 08:55
Show Gist options
  • Save danguilherme/7124166498a2a024b66f43eb0427ea34 to your computer and use it in GitHub Desktop.
Save danguilherme/7124166498a2a024b66f43eb0427ea34 to your computer and use it in GitHub Desktop.
Imperative vs Declarative
function waitSingleWidgetInVirtualTree(
options: MacroApiOptions,
scope: ScopeItem[] = [],
callback: (
(error: Error | null, virtualTreeNode: VirtualTreeNode | null) => void
)
) {
let unsubscribeFromStore: (() => void) | null = null;
function stopWaitingSingleWidgetInVirtualTree() {
if (unsubscribeFromStore) {
unsubscribeFromStore();
}
}
let virtualTree: VirtualTreeNode | null = null;
try {
virtualTree = findSingleWidgetInVirtualTree(
options,
scope
);
} catch (e) {
callback(e, null);
return stopWaitingSingleWidgetInVirtualTree;
}
if (virtualTree) {
callback(null, virtualTree);
return stopWaitingSingleWidgetInVirtualTree;
}
unsubscribeFromStore = options.subscribe(() => {
let virtualTree: VirtualTreeNode | null = null;
try {
virtualTree = findSingleWidgetInVirtualTree(
options,
scope
);
} catch (e) {
callback(e, null);
stopWaitingSingleWidgetInVirtualTree();
}
if (virtualTree) {
callback(null, virtualTree);
stopWaitingSingleWidgetInVirtualTree();
}
});
return stopWaitingSingleWidgetInVirtualTree;
}
function waitSingleWidgetInVirtualTree(
options: MacroApiOptions,
scope: ScopeItem[] = []
) {
let stateChange$ = getStoreChanges(options)
.pipe(
throttleTime(200, undefined, {
leading: true,
trailing: true
})
);
return stateChange$.pipe(
startWith(),
switchMapTo(findSingleWidgetInVirtualTree$(options, scope)),
filter(notNull),
first()
);
}
function getStoreChanges({subscribe}: MacroApiOptions) {
return new Observable<void>(observer => {
let unsubscribe = subscribe(() => observer.next());
return () => unsubscribe();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment