UNPKG

wechaty-redux

Version:

Wechaty Redux Plugin Powered By Ducks

85 lines 3.03 kB
import { Observable, Subject, } from 'rxjs'; import * as duck from '../duck/mod.js'; const puppetRef = new Map(); const increasePuppetReferenceInRegistry = (registry) => (puppet) => { const counter = puppetRef.get(puppet.id) ?? 0; const incCounter = counter + 1; if (incCounter === 1) { registry.set(puppet.id, puppet); } puppetRef.set(puppet.id, incCounter); return incCounter; }; const decreasePuppetReferenceInRegistry = (registry) => (puppet) => { const counter = puppetRef.get(puppet.id) ?? 0; const decCounter = counter - 1; puppetRef.set(puppet.id, decCounter); if (decCounter <= 0) { registry.delete(puppet.id); puppetRef.delete(puppet.id); } return decCounter; }; /** * Puppet will be automatic registered/deregistered inside the RxJS operator * * - Creating new operators from scratch * @see https://rxjs.dev/guide/operators * */ const registerPuppetInRegistry = (registry) => (puppet, options) => (observable) => new Observable(subscriber => { /** * For emitting the `RregisterPuppet` action */ const proxySubject = new Subject(); /** * Chain the subscription to the observable */ const proxySubscription = observable.subscribe(proxySubject); const finalSubscription = proxySubject.subscribe(subscriber); const counter = increasePuppetReferenceInRegistry(registry)(puppet); /** * Emit `RegisterPuppet` action when first time subscribe to the puppet */ if (counter === 1) { proxySubject.next(duck.actions.REGISTER_PUPPET_COMMAND(puppet.id)); if (options?.store && options.wechaty) { options.store.dispatch(duck.actions.BIND_WECHATY_PUPPET_COMMAND({ puppetId: puppet.id, wechatyId: options.wechaty.id, })); } } /** * Return the teardown logic. * * This will be invoked when the result errors, completes, or is unsubscribed. */ return () => { finalSubscription.unsubscribe(); proxySubscription.unsubscribe(); /** * Cleanup puppet in registry with reference counter */ const counter = decreasePuppetReferenceInRegistry(registry)(puppet); if (counter <= 0) { if (options?.store) { /** * Unbind Wechaty <> Puppet */ if (options.wechaty) { options.store.dispatch(duck.actions.UNBIND_WECHATY_PUPPET_COMMAND({ puppetId: puppet.id, wechatyId: options.wechaty.id, })); } /** * Deregister Puppet */ options.store.dispatch(duck.actions.DEREGISTER_PUPPET_COMMAND(puppet.id)); } } }; }); export { registerPuppetInRegistry, increasePuppetReferenceInRegistry, decreasePuppetReferenceInRegistry, puppetRef, }; //# sourceMappingURL=register-puppet.js.map