Skip to content

Instantly share code, notes, and snippets.

@johnrees
Created June 13, 2018 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnrees/2d1c6743806a5972456ffdef688fddc8 to your computer and use it in GitHub Desktop.
Save johnrees/2d1c6743806a5972456ffdef688fddc8 to your computer and use it in GitHub Desktop.
playing with callbags
enum Type {
START,
DATA,
END
}
type Callbag = (type: Type, payload: any) => void;
const producer: Callbag = (type, payload) => {
if (type === Type.START) {
const consumer = payload
let i = 0;
let handle;
consumer(Type.START, (t, p) => {
if (t === Type.END) clearInterval(handle)
if (t === Type.DATA) i = p
})
handle = setInterval(() => {
consumer(Type.DATA, i++)
}, 1000)
}
}
const consumer: Callbag = (type, payload) => {
if (type === Type.START) {
const cb = payload;
setTimeout(() => { cb(Type.DATA, 17) }, 3100)
setTimeout(() => { cb(Type.END) }, 7100)
} else if (type === Type.DATA) {
console.log(payload)
}
}
producer(Type.START, consumer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment