-
-
Save flipjs/68e001706a59fa96329b181b0406dd6e to your computer and use it in GitHub Desktop.
How to wait for burgers (response to http://jlongster.com/Two-Weird-Tricks-with-Redux)
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
function* displayer() { | |
const MaxToasts = 3; | |
const ToastDisplayTime = 4000; | |
let pendingToasts = []; | |
let activeToasts = []; | |
function* displayToast(toast) { | |
if ( activeToasts >= MaxToasts ) { | |
throw new Error("can't display more than " + MaxToasts + " at the same time"); | |
} | |
activeToasts = [...activeToasts,toast]; | |
yield put(events.toastDisplayed(toast)); | |
yield call(delay,ToastDisplayTime); | |
yield put(events.toastHidden(toast)); | |
activeToasts = _.without(activeToasts,toast); | |
} | |
function* toastRequestsWatcher() { | |
while ( true ) { | |
const event = yield take(Names.TOAST_DISPLAY_REQUESTED); | |
const newToast = event.data.toastData; | |
pendingToasts = [...pendingToasts,newToast]; | |
} | |
} | |
function* toastScheduler() { | |
while ( true ) { | |
if ( activeToasts.length < MaxToasts && pendingToasts.length > 0 ) { | |
const [firstToast,...remainingToasts] = pendingToasts; | |
pendingToasts = remainingToasts; | |
yield fork(displayToast,firstToast); | |
// Add little delay so that 2 concurrent 2 toast requests aren't display at the same time | |
yield call(delay,300); | |
} | |
else { | |
yield call(delay,50); | |
} | |
} | |
} | |
yield [ | |
call(toastRequestsWatcher), | |
call(toastScheduler) | |
] | |
} | |
export default function* toastSaga() { | |
yield [ | |
call(watcher), | |
call(displayer) | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment