How to use the rx.Observable.defer function in rx

To help you get started, we’ve selected a few rx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github freeCodeCamp / freeCodeCamp / api-server / common / models / user.js View on Github external
// newEmail is not associated with this user, and
    // this attempt to change email is the first or
    // previous attempts have expired
    if (
      !isOwnEmail ||
      (isOwnEmail && !isVerifiedEmail) ||
      (isResendUpdateToSameEmail && !isLinkSentWithinLimit)
    ) {
      const updateConfig = {
        newEmail,
        emailVerified: false,
        emailVerifyTTL: new Date()
      };

      // defer prevents the promise from firing prematurely (before subscribe)
      return Observable.defer(() => User.doesExist(null, newEmail))
        .do(exists => {
          if (exists && !isOwnEmail) {
            // newEmail is not associated with this account,
            // but is associated with different account
            throw wrapHandledError(new Error('email already in use'), {
              type: 'info',
              message: `${newEmail} is already associated with another account.`
            });
          }
        })
        .flatMap(() => {
          const updatePromise = new Promise((resolve, reject) =>
            this.updateAttributes(updateConfig, err => {
              if (err) {
                return reject(err);
              }
github freeCodeCamp / freeCodeCamp / server / services / user.js View on Github external
config,
      cb) {
      const queryUser = req.user;
      console.log(queryUser.completedChallengeCount)
      const source = queryUser && Observable.forkJoin(
        queryUser.getCompletedChallenges$(),
        queryUser.getPoints$(),
        (completedChallenges, progressTimestamps) => ({
          completedChallenges,
          progress: getProgress(progressTimestamps, queryUser.timezone)
        })
      );
      Observable.if(
        () => !queryUser,
        Observable.of({}),
        Observable.defer(() => source)
          .map(({ completedChallenges, progress }) => ({
            ...queryUser.toJSON(),
            ...progress,
            completedChallenges: completedChallenges.map(
              fixCompletedChallengeItem
            )
          }))
          .map(
            user => ({
              entities: {
                user: {
                  [user.username]: {
                    ..._.pick(user, userPropsForSession),
                    isEmailVerified: !!user.emailVerified,
                    isGithub: !!user.githubProfile,
                    isLinkedIn: !!user.linkedin,
github freeCodeCamp / freeCodeCamp / common / app / routes / Challenges / utils / frame.js View on Github external
export const runTestsInTestFrame = (document, tests) => Observable.defer(() => {
  const { contentDocument: frame } = document.getElementById(testId);
  return frame.__runTests(tests);
});
github freeCodeCamp / freeCodeCamp / api-server / common / utils / wait-for-epics.js View on Github external
export default function waitForEpics(epicMiddleware) {
  return Observable.defer(() => {
    log('calling actions onCompleted');
    epicMiddleware.end();
    return Observable.merge(epicMiddleware);
  })
    .last({ defaultValue: null })
    .map(() => epicMiddleware.restart());
}
github freeCodeCamp / freeCodeCamp / common / app / routes / Challenges / redux / completion-epic.js View on Github external
function postChallenge(url, username, _csrf, challengeInfo) {
  return Observable.if(
    () => !!username,
    Observable.defer(() => {
      const body = { ...challengeInfo, _csrf };
      const saveChallenge = postJSON$(url, body)
        .retry(3)
        .map(({ points, lastUpdated, completedDate }) =>
          submitChallengeComplete(
            username,
            points,
            { ...challengeInfo, lastUpdated, completedDate }
          )
        )
        .catch(createErrorObservable);
      const challengeCompleted = Observable.of(moveToNextChallenge());
      return Observable.merge(saveChallenge, challengeCompleted)
        .startWith({ type: types.submitChallenge.start });
    }),
    Observable.of(moveToNextChallenge())
github marinels / webrx-react / src / Components / React / BaseViewModel.ts View on Github external
public getObservableOrAlert(
    observableFactory: () => Observable,
    header: string,
    style?: string,
    timeout?: number,
    errorFormatter?: (e: TError) => string,
  ) {

    return Observable
      .defer(observableFactory)
      .catch(err => {
        this.alertForError(err, header, style, timeout, errorFormatter);

        return Observable.empty();
      });
  }
github freeCodeCamp / freeCodeCamp / api-server / common / models / user.js View on Github external
User.prototype.updateMyUsername = function updateMyUsername(newUsername) {
    return Observable.defer(() => {
      const isOwnUsername = isTheSame(newUsername.toLowerCase(), this.username);
      if (isOwnUsername) {
        return Observable.of(dedent`
          ${newUsername} is already associated with this account.
          `);
      }
      return Observable.fromPromise(User.doesExist(newUsername.toLowerCase()));
    }).flatMap(boolOrMessage => {
      if (typeof boolOrMessage === 'string') {
        return Observable.of(boolOrMessage);
      }
      if (boolOrMessage) {
        return Observable.of(dedent`
        ${newUsername} is already associated with a different account.
        `);
      }
github freeCodeCamp / freeCodeCamp / api-server / server / boot / user.js View on Github external
const source =
      queryUser &&
      Observable.forkJoin(
        queryUser.getCompletedChallenges$(),
        queryUser.getPoints$(),
        Donation.getCurrentActiveDonationCount$(),
        (completedChallenges, progressTimestamps, activeDonations) => ({
          activeDonations,
          completedChallenges,
          progress: getProgress(progressTimestamps, queryUser.timezone)
        })
      );
    Observable.if(
      () => !queryUser,
      Observable.of({ user: {}, result: '' }),
      Observable.defer(() => source)
        .map(({ activeDonations, completedChallenges, progress }) => ({
          user: {
            ...queryUser.toJSON(),
            ...progress,
            completedChallenges: completedChallenges.map(
              fixCompletedChallengeItem
            )
          },
          sessionMeta: { activeDonations }
        }))
        .map(({ user, sessionMeta }) => ({
          user: {
            [user.username]: {
              ...pick(user, userPropsForSession),
              isEmailVerified: !!user.emailVerified,
              isGithub: !!user.githubProfile,