本文整理匯總了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);
}
}
}
示例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 })
}
}
}
}
示例3: fork
yield fork(function* () {
const { success } = yield race({ success: take(SIGNUP_SUCCESS), otherwise: take(SIGNUP_FAILURE) });
if (success) {
yield call(createToken, { email, password });
}
});
示例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)
});
}
});
示例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;
}
}
}
示例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)
})
示例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);
}
}
示例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)
}
}
示例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);
}
}
}
}
示例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();
}
}
示例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);
}
示例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')));
}
}
}
示例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)
}
}
示例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());
}
}
示例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)); // 刷新特定文章
}
}
}