Created
June 13, 2018 17:11
-
-
Save johnrees/2d1c6743806a5972456ffdef688fddc8 to your computer and use it in GitHub Desktop.
playing with callbags
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
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