Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { actionChannel, all, put, race, take } from 'redux-saga/effects';
- export function createAsyncListener(
- listenerId: string,
- closeListenerId: string,
- hookId: string | string[] = listenerId
- ) {
- return function*() {
- while (true) {
- const callbackAction = yield take(listenerId);
- if (callbackAction && typeof callbackAction.payload === 'function') {
- const channel = yield actionChannel(hookId);
- try {
- while (true) {
- const [result, cancel] = yield race([
- take(channel),
- take(closeListenerId)
- ]);
- if (cancel) {
- break;
- }
- callbackAction.payload(result.payload);
- }
- } catch (e) {
- console.log(e);
- } finally {
- channel.close();
- }
- }
- }
- };
- }
- export function createWaitHooksListener(
- listenerId: string,
- closeListenerId: string,
- hookIds: string[]
- ) {
- return function*() {
- while (true) {
- const callbackAction = yield take(listenerId);
- if (typeof callbackAction.payload === 'function') {
- while (true) {
- const [results, unsubscribe] = yield race([
- all(hookIds.map(_hookId => take(_hookId))),
- take(closeListenerId)
- ]);
- if (unsubscribe) {
- break;
- }
- callbackAction.payload(
- results.map(result => {
- return result.payload;
- })
- );
- }
- }
- }
- };
- }
- export function createListenerActionCreators<T extends any = any>(
- listenerId: string,
- closeListenerId: string,
- hookId: string = listenerId
- ) {
- const onListener = (callback: (result?: T) => void) => ({
- type: listenerId,
- payload: callback
- });
- const closeListener = () => ({
- type: closeListenerId
- });
- const emit = (result?: T, type?: string) => {
- return put({
- type: type || hookId,
- payload: result
- });
- };
- return [onListener, closeListener, emit] as [
- typeof onListener,
- typeof closeListener,
- typeof emit
- ];
- }
- export function generateListenerSagaAndActionCreators<T extends any = any>(
- listenerId: string,
- closeListenerId: string,
- hookId: string | string[] = listenerId,
- option?: {
- waitAll?: true;
- }
- ) {
- const [onListener, closeListener, emit] = createListenerActionCreators<T>(
- listenerId,
- closeListenerId,
- listenerId
- );
- const listenerSaga =
- option && option.waitAll && Array.isArray(hookId)
- ? createWaitHooksListener(listenerId, closeListenerId, hookId)
- : createAsyncListener(listenerId, closeListenerId, hookId);
- return [listenerSaga, onListener, closeListener, emit] as [
- typeof listenerSaga,
- typeof onListener,
- typeof closeListener,
- typeof emit
- ];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement