javascript RxJS史诗提供者

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript RxJS史诗提供者相关的知识,希望对你有一定的参考价值。

import React, {createContext} from 'react'
const EpicContext = createContext({setEpic:(epic) =>{console.log('No provider for epic detected')}})
export default EpicContext
export const withEpicContext = (Component) => ({children, ...props}) =>
 ( 
 <EpicContext.Consumer>
  {
    ({setEpic}) => (
        <Component {...props} setEpic={setEpic}>{children}</Component>
    )
  }
  </EpicContext.Consumer>
    )
import React from 'react'
import {createStore, applyMiddleware} from'redux'
import {createEpicMiddleware} from 'redux-observable'
import { filter, mapTo, takeUntil, switchMap, mergeMap}  from 'rxjs/operators'
import {BehaviorSubject} from 'rxjs'
import {interval} from 'rxjs'
import rootReducer from './src/ducks/BaseReducer'
import EpicContext from './src/components/EpicContext'

const EpicProvider = EpicContext.Provider
const observableMiddleware = createEpicMiddleware()
const store = createStore(rootReducer,{ num:1 }, applyMiddleware(observableMiddleware))
// Set initial action stream
const epic$ = new BehaviorSubject((action$) => {
  return interval(1000).pipe(mapTo({type:"PING"}), takeUntil(action$.pipe(filter(({type}) => type === "PONG"))))
})
const setEpic = (epic) => {epic$.next(epic)}
// Use switchMap to switch between epics or mergeMap to add new epics
const rootEpic = (action$, state$) => epic$.pipe(switchMap(epic => epic(action$, state$)))

observableMiddleware.run(rootEpic)
export let wrapRootElement = ({element}) => {
  return (
  <EpicProvider value={{setEpic}}>
    <Provider store={store}>{element}</Provider>
  </EpicProvider>
  )
}
import {withEpic} from './EpicContext'
import {of} from 'rxjs'
import epic from './anotherEpic'
export default withEpic(epic)(({setEpic}) => {
  <button onClick={() => {setEpic(action$ => {
    return of({type: 'PONG'})
  })}}
  >START PONG</button>
  
})

以上是关于javascript RxJS史诗提供者的主要内容,如果未能解决你的问题,请参考以下文章

RxJS:禁止在效果和史诗中使用不安全的 catch 并请求嵌套

为啥我的 redux-observable 史诗没有被触发?

如何在同一个史诗中调度多个动作

在 Redux Observable 中保持史诗直到收到操作

React redux-observable:以史诗般的方式进行顺序 API 调用

RXJS Observable 数组上的简单过滤器