LaunchDarkly feature flag service in Angular using RxJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() { | |
await this.client.close(); | |
} | |
initialize(): void { | |
const user = { | |
anonymous: true | |
} as LaunchDarkly.LDUser; | |
this.client = LaunchDarkly.initialize(environment.launchDarklyClientId, user); | |
} | |
getFlag(flagKey: string, defaultValue: LDFlagValue = false): Observable<LDFlagValue> { | |
const fetchFlag = new Subject<void>(); | |
this.client.on(`change:${flagKey}`, () => { | |
fetchFlag.next(); | |
}); | |
this.client.waitUntilReady().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
How do you test “this.client.on” event? Any example code will be appreciated?
https://gist.github.com/cookavich/a8d99e8fa37b11ce8e0f3592d7e1e0c7#file-feature-flag-service-ts-L27