當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript effects.take函數代碼示例

本文整理匯總了TypeScript中redux-saga/effects.take函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript take函數的具體用法?TypeScript take怎麽用?TypeScript take使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了take函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: watchDelete

function* watchDelete() {
  while (true) {
    const { id, formId } = yield take(DELETE_SUBMISSION);
    const { auth: { api } } = yield select();

    try {
      const [{ payload: { prevRowId } }] = yield [
        take(action => action.query === 'SUBMISSIONS' && action.type === ROW_REMOVED && action.payload.row.id === id),
        api.deleteSubmission(id),
      ];

      const { submissions } = yield select();

      if (prevRowId) {
        const nextRow = submissions.rows.get(submissions.rows.findIndex(row => row.id === prevRowId) + 1);

        var redirectTo = nextRow ? nextRow.id : prevRowId;
      } else {
        var redirectTo = submissions.rows.isEmpty() ? '' : submissions.rows.first().id;
      }

      yield put(routeActions.push(`forms/${formId}/submissions/${redirectTo}`));
    } catch(error) {
      console.log(error);
    }
  }
}
開發者ID:rosendi,項目名稱:figure,代碼行數:27,代碼來源:submissions.ts

示例2: botSaga

export default function* botSaga(tankId: TankId) {
  const ctx = new Bot(tankId)
  try {
    yield takeEvery(hitPredicate, hitHandler)
    const result = yield race({
      service: all([
        generateBulletCompleteNote(),
        directionController(tankId, ctx.directionControllerCallback),
        fireController(tankId, ctx.fireControllerCallback),
        AIWorkerSaga(ctx),
      ]),
      killed: take(killedPredicate),
      endGame: take(A.EndGame),
    })
    const tank: TankRecord = yield select(selectors.tank, tankId)
    yield put(actions.setTankToDead(tankId))
    if (result.killed) {
      yield explosionFromTank(tank)
      if (result.killed.method === 'bullet') {
        yield scoreFromKillTank(tank)
      }
    }
    yield put(actions.reqAddBot())
  } finally {
    const tank: TankRecord = yield select(selectors.tank, tankId)
    if (tank && tank.alive) {
      yield put(actions.setTankToDead(tankId))
    }
  }

  function hitPredicate(action: actions.Action) {
    return action.type === actions.A.Hit && action.targetTank.tankId === tankId
  }

  function* hitHandler(action: actions.Hit) {
    const tank: TankRecord = yield select(selectors.tank, tankId)
    DEV.ASSERT && console.assert(tank != null)
    if (tank.hp > 1) {
      yield put(actions.hurt(tank))
    } else {
      const { sourceTank, targetTank } = action
      yield put(actions.kill(targetTank, sourceTank, 'bullet'))
    }
  }

  function killedPredicate(action: actions.Action) {
    return action.type === actions.A.Kill && action.targetTank.tankId === tankId
  }

  function* generateBulletCompleteNote() {
    while (true) {
      const { bulletId }: actions.BeforeRemoveBullet = yield take(actions.A.BeforeRemoveBullet)
      const { bullets }: State = yield select()
      const bullet = bullets.get(bulletId)
      if (bullet.tankId === tankId) {
        ctx.noteChannel.put({ type: 'bullet-complete', bullet })
      }
    }
  }
}
開發者ID:socoolxin,項目名稱:battle-city,代碼行數:60,代碼來源:BotSaga.ts

示例3: fork

  yield fork(function* () {
    const { success } = yield race({ success: take(SIGNUP_SUCCESS), otherwise: take(SIGNUP_FAILURE) });

    if (success) {
      yield call(createToken, { email, password });
    }
  });
開發者ID:rosendi,項目名稱:figure,代碼行數:7,代碼來源:auth.ts

示例4: fork

  yield fork(function*() {

    let prevState: ApplicationState;
    yield take(TRIED_LOADING_APP_STATE);

    while(true) {
      yield take();
      yield call(delay, PERSIST_DELAY_TIMEOUT);
      const state: ApplicationState = yield select();
      if (prevState === state) {
        continue;
      }

      prevState = state;

      // convert to a POJO object in case there are non serializable
      // object somehow in the application store. For the most part -- everything should be
      // a POJO with very few exceptions. For cases where data cannot be converted into a plain object, the application will need to re-hydrate the non-serializable data on startup. 
      const pojoState = serializeApplicationState(state);
      const { apiHost }: ApplicationState = state;

      yield call(fetch, apiHost + "/storage/" + state.storageNamespace + SAVE_KEY, {
        method: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        } as any,
        body: JSON.stringify(pojoState)
      });
    }
  });  
開發者ID:cryptobuks,項目名稱:tandem,代碼行數:31,代碼來源:api.ts

示例5: authFlow

export function* authFlow() {
  yield fork(watchStorage);
  yield fork(redirectOnAuth);

  while (true) {
    const token = auth.retrieveToken();

    if (token) {
      const state = yield select(state => state.auth);

      if (!state || state.token.toString() !== token.toString()) {
        yield put(signinSuccess(token, false));
      }

      yield call(watchExpiration, token.expiresIn);
    } else {
      yield call(purgeToken, false);
    }

    const { signin, signup } = yield race({ signin: take(SIGNIN), signup: take(SIGNUP), overwise: take(SIGNIN_SUCCESS) });

    if (signin) {
      yield fork(submitSigninForm, signin.resolve, signin.reject);
      yield call(createToken, signin);
      continue;
    }

    if (signup) {
      yield fork(submitSignupForm, signup.resolve, signup.reject);
      yield call(createUser, signup);
      continue;
    }
  }
}
開發者ID:rosendi,項目名稱:figure,代碼行數:34,代碼來源:auth.ts

示例6: it

 it('should add recommendations page if recommendations were returned', () => {
     return expectSaga(recommendationsSaga(mockStoreApi))
         .withState({
             currentUser: {
                 status: 'LOGGED_IN',
                 token: '',
             },
             ignored: [],
             owned: [],
         })
         .provide([
             [call(mockStoreApi.getRecommendations, ''), { data: mockRecommendations }],
             [call(createScrollChannel), mockScrollChannel],
             [take(mockScrollChannel), mockScrollInfo299px],
             [matchers.call.fn(getRecommendationsPage), mockPage],
             [take(mockScrollChannel), mockScrollInfo299px],
             [matchers.call.fn(getRecommendationsPage), mockPage],
         ])
         .put(productActions.add(mockPage.products))
         .put(recommendationsActions.addPage(mockPage.items))
         .delay(100)
         .put(productActions.add(mockPage.products))
         .put(recommendationsActions.addPage(mockPage.items))
         .silentRun(150)
 })
開發者ID:steam-react,項目名稱:steam,代碼行數:25,代碼來源:recommendations.test.ts

示例7: handleOpenTandem

function* handleOpenTandem() {
  yield take(OPEN_TANDEM_EXECUTED);

  let state: ExtensionState = yield select();
  var textDocumentContentProvider = {
    provideTextDocumentContent(uri) {
      return `
        <html>
          <head>
            <title>Tandem</title>
          </head>
          <body>
            <iframe src="${getIndexUrl(state)}" style="position:absolute;left:0;top:0;width:100vw; height: 100%; border: none;"></iframe>
          </body>
        </html>
      `;
    },
  };

  state.context.subscriptions.push(
    vscode.workspace.registerTextDocumentContentProvider(
      PREVIEW_NAME,
      textDocumentContentProvider)
  );

  while(true) {
    yield call(vscode.commands.executeCommand,
      "vscode.previewHtml",
      PREVIEW_URI,
      vscode.ViewColumn.Two,
      "Tandem"
    );
    yield take(OPEN_TANDEM_EXECUTED);
  }
}
開發者ID:cryptobuks,項目名稱:tandem,代碼行數:35,代碼來源:vscode.ts

示例8: watchCreateAndRemoveLastPosition

// use channel to make sure every create/remove run one by one
function* watchCreateAndRemoveLastPosition(): SagaIterator {
  try {
    const createLastPositionChan: TakeableChannel<{}> = yield actionChannel(
      getType(lastPositionsCreator.createLastPosition)
    )
    const removeLastPositionChan: TakeableChannel<{}> = yield actionChannel(
      getType(lastPositionsCreator.removeLastPosition)
    )
    while (true) {
      const [createLastPositionAction, removeLastPositionAction]: [
        ReturnType<typeof lastPositionsCreator.createLastPosition> | void,
        ReturnType<typeof lastPositionsCreator.removeLastPosition> | void
      ] = yield race([take(createLastPositionChan), take(removeLastPositionChan)])

      if (createLastPositionAction) {
        yield call(createLastPosition, createLastPositionAction)
      }

      if (removeLastPositionAction) {
        yield call(removeLastPosition, removeLastPositionAction)
      }
    }
  } catch (err) {
    console.error(err)
  }
}
開發者ID:foray1010,項目名稱:Popup-my-Bookmarks,代碼行數:27,代碼來源:saga.ts

示例9: loginFlow

export function* loginFlow() {
  window.beforeLogin = '/';
  let previousSession = null;
  yield take(LOCATION_CHANGE);
  while (true) { // eslint-disable-line no-constant-condition
    console.log('while true ', new Date());
    const session = authAgent.getSession();
    let location = yield select(makeSelectLocation());
    location = location.pathname;

    if (session !== null)
    {
      if (session !== previousSession) {
        yield put({type: AUTHENTICATED});
      }
      if (previousSession === null) {
        console.log('writing new session');
        previousSession = session;
      }
      console.log('Session:', session);
      if (location === '/login')
      {
        if (window.beforeLogin === '/login' || window.beforeLogin === '/logout')
          window.beforeLogin = '/';
        yield put(push(window.beforeLogin))
      }
      else
      {
        window.beforeLogin = location;
      }
      yield take(LOGOUT);
      try {
        yield call([authAgent,authAgent.logout]);
        yield put({type : LOGGED_OUT});
      }
      catch (e)
      {
        console.log('logout error!', e);
      }
    }
    else
    {
      if (location !== '/login') {
        window.beforeLogin = location;
        yield put(push('/login'));
      }
      const { login, password} = yield take(AUTH);

      try { //context call
        yield call([authAgent,authAgent.auth], login, password);
      }
      catch(e)
      {
        console.log('login error!',e);
      }

    }
  }
}
開發者ID:,項目名稱:,代碼行數:59,代碼來源:

示例10: submitSigninForm

function* submitSigninForm(resolve, reject) {
  const { failure } = yield race({ success: take(SIGNIN_SUCCESS), failure: take(SIGNIN_FAILURE)});

  if (failure) {
    typeof failure.reason.message === 'object' ? reject(failure.reason.message) : reject({ _error: failure.reason.message });
  } else {
    resolve();
  }
}
開發者ID:rosendi,項目名稱:figure,代碼行數:9,代碼來源:auth.ts

示例11: testTake

function* testTake(): SagaIterator {
  yield take();
  yield take('my-action');
  yield take((action: Action) => action.type === 'my-action');
  yield take(isMyAction);

  // typings:expect-error
  yield take(() => {});

  yield take(stringableActionCreator);

  yield take([
    'my-action',
    (action: Action) => action.type === 'my-action',
    stringableActionCreator,
    isMyAction,
  ]);

  // typings:expect-error
  yield take([() => {}]);

  yield takeMaybe([
    'my-action',
    (action: Action) => action.type === 'my-action',
    stringableActionCreator,
    isMyAction,
  ]);

  yield take(channel);

  yield takeMaybe(channel);
}
開發者ID:woota,項目名稱:redux-saga,代碼行數:32,代碼來源:effects.ts

示例12: redirectOnAuth

function* redirectOnAuth() {
  while (true) {
    const { signin, logout } = yield race({ signin: take(SIGNIN_SUCCESS), logout: take(LOGOUT_SUCCESS)});

    if (signin) {
      signin.performRedirect && (yield put(routeActions.push(yield call(refererPath, '/'))));
    } else {
      logout.performRedirect && (yield put(routeActions.push('/signin')));
    }
  }
}
開發者ID:rosendi,項目名稱:figure,代碼行數:11,代碼來源:auth.ts

示例13: main

  function* main() {
    while( yield take('START_BACKGROUND_SYNC') ) {
      // starts the task in the background
      const bgSyncTask = yield fork(bgSync)

      // wait for the user stop action
      yield take('STOP_BACKGROUND_SYNC')
      // user clicked stop. cancel the background task
      // this will throw a SagaCancellationException into the forked bgSync
      // task
      yield cancel(bgSyncTask)
    }
  }
開發者ID:HawkHouseIntegration,項目名稱:DefinitelyTyped,代碼行數:13,代碼來源:redux-saga-tests.ts

示例14: refreshTagsDeal

export function* refreshTagsDeal(): any {
	while (true) {
		yield race({
			login: take(LOGIN_SUCCESS),
			addTag: take(ADD_WIKI_SPECTAG_SUCCESS),
			modifyTag: take(CHANGE_WIKI_SPEC_TAG_SUCCESS),
			delTag: take(DEL_WIKI_SPECTAG_SUCCESS),
		});

		// 觸發查詢
		yield put(queryTags());
	}
}
開發者ID:weiweiwitch,項目名稱:third-lab,代碼行數:13,代碼來源:tags.ts

示例15: refreshSpecPostDeal

export function* refreshSpecPostDeal(): any {
	while (true) {
		const {change, move2NewTag} = yield race({
			change: take(CHG_WIKI_SPECPOST_SUCCESS),
			move2NewTag: take(MOVE_WIKI_POST_2_NEW_TAG_SUCCESS),
		});
		if (change) {
			yield put(querySpecPost(change.payload.id)); // 刷新特定文章
		} else if (move2NewTag) {
			yield put(querySpecPost(move2NewTag.payload.id)); // 刷新特定文章
		}

	}
}
開發者ID:weiweiwitch,項目名稱:third-lab,代碼行數:14,代碼來源:posts.ts


注:本文中的redux-saga/effects.take函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。