import { call , take , fork , takeLatest , put , } from 'redux-saga/effects' ; import { eventChannel , END } from 'redux-saga' ; import { initRemoteWallet , stopWallet } from '@core/api' ; import { BackgroundEvent , RemoteResponse , RPCEvent } from '@core/types' ; import { handleConnect , handleProgress } from '@app/containers/Auth/store/saga' ; import { handleTotals , handleAssets } from '@app/containers/Wallet/store/saga' ; import { handleTransactions } from '@app/containers/Transactions/store/saga' ; import { actions } from '@app/shared/store/index' ; import { navigate } from '@app/shared/store/actions' ; import { ROUTES } from '@app/shared/constants' ; import { setSyncedWalletState } from '@app/containers/Auth/store/actions' ; export function remoteEventChannel ( ) { return eventChannel ( ( emitter ) => { const port = initRemoteWallet ( ) ; const handler = ( data ) => { emitter ( data ) ; } ; port . onMessage . addListener ( handler ) ; const unsubscribe = ( ) => { port . onMessage . removeListener ( handler ) ; emitter ( END ) ; } ; return unsubscribe ; } ) ; } function * stopWalletSaga ( ) { yield put ( setSyncedWalletState ( false ) ) ; yield put ( navigate ( ROUTES . AUTH . LOGIN ) ) ; yield call ( stopWallet ) ; } function * sharedSaga ( ) { const remoteChannel = yield call ( remoteEventChannel ) ; yield takeLatest ( actions . stopWallet , stopWalletSaga ) ; while ( true ) { try { const payload = yield take ( remoteChannel ) ; switch ( payload . id ) { case BackgroundEvent . CONNECTED : yield fork ( handleConnect , payload . result ) ; break ; case RPCEvent . SYNC_PROGRESS : yield fork ( handleProgress , payload . result ) ; break ; case RPCEvent . ASSETS_CHANGED : yield fork ( handleAssets , payload . result ) ; break ; case RPCEvent . SYSTEM_STATE : yield fork ( handleTotals ) ; break ; case RPCEvent . TXS_CHANGED : yield fork ( handleTransactions , payload . result ) ; break ; default : break ; } } catch ( err ) { remoteChannel . close ( ) ; } } } export default sharedSaga ;