flow.or()
Using flow.or(), two or more flow objects can be combined into one. The callback pipeline then receives triggers from all included flows.
Syntax
flow.or(thenable);
Parameters
- thenable
- A thenable (such as another
Flow
or a Promise) whose trigger is to be included in flow's callback pipeline. Upon stopping flow, the thenable's .stop() method is called (if it exists), allowing all relevant flows to be cleaned up properly.
Return value
The same Flow
object the method was called on, allowing for method chaining.
Examples
Timeouts
The .or() method can be beautifully combined with timeout()
to create timeouts for certain events. For example, say we have a toast popup that we need to close when either the user clicks it or when it's been shown for 5 seconds. We might do something like
<title>toast-popup</title>
<meta method="show">
<template mode="closed">
<div id="message" .hidden="!$.shown">
<slot></slot>
</div>
</template>
<script>
$.shown = false;
const message = query('#message');
$.show = purify(() => {
$.shown = true;
when(message).clicks().or(timeout(5000))
.once()
.then(() => $.shown = false);
});
</script>
We combine it with purify
to allow the .show() method from cleaning up the listener and timeout created in a previous call, which allows us to call it multiple times in succession safely. The resulting custom element toggles the hidden attribute off when the .show() method is called, and adds the attribute back when either the message is clicked or the specified timeout() elapses.
Usage notes
When calling flow.or(other), the argument other is bundled into flow, but not the other way around; the other flow isn't aware of this. As such, stopping the other does not stop flow, it simply prevents the other from sending any more triggers into flow's callback pipeline.
See also