Skip to content

Instantly share code, notes, and snippets.

@nornagon
Last active June 12, 2017 01:38
Show Gist options
  • Save nornagon/42c595984da200e8c17d4da5665f5027 to your computer and use it in GitHub Desktop.
Save nornagon/42c595984da200e8c17d4da5665f5027 to your computer and use it in GitHub Desktop.
Switching between apps based on state in Cycle.js
export function App(sources) {
const appSinks$ = sources.onion.state$
.startWith({name: null})
.map(state => state.name)
// drop repeats to prevent Main() being re-called every time the state changes
.compose(dropRepeats())
.map(name => {
if (name == null) {
return SetName(sources);
} else {
return Main(sources);
}
})
// "current app" needs to be a memory stream, otherwise only one
// of the appSinks$ subscriptions below will receive the first event.
.remember();
return {
onion: appSinks$.map(s => s.onion).flatten(),
DOM: appSinks$.map(s => s.DOM).flatten(),
}
}
function SetName(sources) {
return {
DOM: xs.of(<div><button>set name</button></div>),
onion: sources.DOM.select('button')
.events('click')
.mapTo(s => {name: "Jeremy"}),
};
}
function Main(sources) {
return {
DOM: sources.onion.state$
.map(state => <div>name is: {state.name}</div>),
onion: xs.empty(),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment