Skip to content

Instantly share code, notes, and snippets.

@awto
Last active May 28, 2016 11:16
Show Gist options
  • Save awto/9f5337fcf205df335c92f93a859e2fdf to your computer and use it in GitHub Desktop.
Save awto/9f5337fcf205df335c92f93a859e2fdf to your computer and use it in GitHub Desktop.
rxjs used with burrido as do notation
/**
* This demonstrates problems of using burrido with most (and in fact with any
* other multi-answer monads). It works only if `most` doesn't contain other
* effect besides pure stream comprehension effects, or effects we don't care
* about.
*/
import {Observable} from 'rx'
import Monad from 'burrido'
const { just: pure, fromPromise,from } = Observable
const { Do: doMerge } = Monad({
pure,
bind: (x, f) => x.flatMap(f)
})
let cnt = 0
/**
* This is a symple and typical use case, we want to update something
* in DB before some other actions. It is simulated just with promise
* with timeout
*/
function updateDb() {
return new Promise(resolve => {
setTimeout(
() => {
console.log(`DB UPDATED ${cnt}`)
resolve(cnt++)
}, 0)
})
}
doMerge(function*() {
// first we want to update something in DB
const m = yield fromPromise(updateDb())
const x = yield from([1,2])
return `${x} ${m}`
}).subscribe(function(res) {
console.log(res)
})
/*
and the output is
```
DB UPDATED 0
1 0
2 0
DB UPDATED 1
DB UPDATED 2
DB UPDATED 3
```
so we updated DB 4 times instead of 1
*/
/*
Things are much worth if the block contains JS side effects. It is of course
nice if there is none, but I don't see why not to use this useful tool in
right places. It also may be accidental making debugging to be very painful.
*/
let i = 0;
doMerge(function*() {
const x = yield from([1,2])
if (i++) {
const y = yield from(['in then'])
return `then ${x} ${y}`
} else {
const y = yield from(['in else'])
return `else ${x} ${y}`
}
}).subscribe(function(res) {
console.log(res)
})
/*
outputs:
```
then 1 in else
then 2 in then
```
so it combined output of `then` branch with value yielded in `else` branch
*/
/**
* And alternative is to use [mfjs compiler](https://github.com/awto/mfjs-compiler),
* it has optionally support for generators syntax. So the source code for generators
* is absolutely the same like in burrido but outpurs correct results in both cases.
* https://gist.github.com/awto/d71bc466884dc9a9a6a93026ce363d17
*
* Namely:
* ```
* DB UPDATED 0
* 1 0
* 2 0
* ```
* and
* ```
* else 1 in else
* then 2 in then
* ```
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment