Skip to content

Instantly share code, notes, and snippets.

@tarqd
Forked from cookavich/feature-flag.service.ts
Last active December 12, 2024 18:52
Show Gist options
  • Save tarqd/1266143029ee311a1f93283b0885a1cc to your computer and use it in GitHub Desktop.
Save tarqd/1266143029ee311a1f93283b0885a1cc to your computer and use it in GitHub Desktop.
LaunchDarkly feature flag service in Angular using RxJS
import { Injectable, OnDestroy } from '@angular/core';
import { environment } from '@environments/environment';
import * as LaunchDarkly from 'launchdarkly-js-client-sdk';
import { LDFlagValue } from 'launchdarkly-js-client-sdk';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class FeatureFlagService implements OnDestroy {
client: LaunchDarkly.LDClient;
async ngOnDestroy() {
// attempt to flush any buffered events
await this.client.flush();
}
initialize(): void {
/* consider replacing this with a method to get the current user and map it to a context */
const context = {
{
kind: "user"
anonymous: true
}
};
this.client = LaunchDarkly.initialize(environment.launchDarklyClientId, context, {
// uncomment to cache flags in local storage
// bootstrap: "localStorage"
});
}
getFlag(flagKey: string, defaultValue: LDFlagValue = false): Observable<LDFlagValue> {
const fetchFlag = new Subject<void>();
this.client.on(`change:${flagKey}`, () => {
fetchFlag.next();
});
// Maximum time to wait for init before contining anyway
const TIMEOUT_SECONDS = 1;
this.client.waitForInitialization(TIMEOUT_SECONDS)
.catch(e => {
console.error("permanent error during initialization, cached or fallback values will be returned")
}).then(() => {
fetchFlag.next();
});
return fetchFlag.pipe(
map(() => {
return this.client.variation(flagKey, defaultValue);
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment