zambezi / caballo-vivo

Glue code for pure RxJS applications to connect with React-Router, and other operators
2 stars 7 forks source link

`cook` (or similarly named) Rx operator? #18

Closed gabrielmontagne closed 5 years ago

gabrielmontagne commented 5 years ago

Hey, @cristiano-belloni what about if we have something like

function cook(reducer) {
    return function cook(source$) {
        return source$.pipe(operators.map(next => R.curry(reducer)(R.__, next)))
    }
} 

So that we can do stuff like,

// intents!
var play$ = new Subject()
var loop$ = new Subject()
var stop$ = new Subject()

var initialState = {
    tracks: [1, 2, 3],
    expensiveThingToCreate: {
        bufferFancyThing: a=>console.log('OMG! side effect', a)
    },
    duration: 0,
    position: 0,
    isLooping: 0
}

player$ = merge(

play$.pipe(cook(play)), 
loop$.pipe(cook(loop))

).pipe(operators.scan(reduceMe, initialState))

player$.subscribe(log('finally!'))

function reduceMe(stuff, doing) {

    return doing(stuff)
}

console.clear()
''

function play({tracks, duration, expensiveThingToCreate, position, isLooping}, what) {

    console.log('play!', what)
    expensiveThingToCreate.bufferFancyThing(new Date())

    return {
        tracks,
        duration,
        expensiveThingToCreate,
        position: position + 1000,
        isLooping
    }

}

function loop({tracks, duration, expensiveThingToCreate, position, isLooping}, shouldLoop) {

    console.log('LOOP!', arguments, shouldLoop)
    expensiveThingToCreate.bufferFancyThing(shouldLoop)

    return {
        tracks,
        duration,
        expensiveThingToCreate,
        position: -1984,
        isLooping: shouldLoop
    }

}

This will allow us to hold transient state using the gut of the RxJS pipes.

cristiano-belloni commented 5 years ago

I moved all my stateful multi-headed ugly wrappers to cook and they cook wonderfully. PR here: https://github.com/zambezi/caballo-vivo/pull/21

We should really document this stuff sooner or later :)

gabrielmontagne commented 5 years ago

Done!