0.4.3 • Published 3 months ago

@oafz/mediator v0.4.3

Weekly downloads
-
License
-
Repository
-
Last release
3 months ago

@oafz/mediator

A simple pub/sub library.

NOTE ⚠

I only publish the source code which written in typescript. My tsconfig.json is here.

Usage

  1. createRequestEmitter

It has only one subscriber.

import { useEffect } from 'react';
import { NavigateOptions, Path, useNavigate } from 'react-router-dom';
import { createRequestEmitter } from '@oafz/mediator';

// only one parameter can be passed
export const navigateRequester = createRequestEmitter<
  | string
  | {
      path: string | Partial<Path>;
      options?: NavigateOptions;
    }
  | number,
  void
>({ name: 'navigate' });

export function NavigatePlugin() {
  const nav = useNavigate();

  useEffect(() => {
    // `receive` method returns a unsubscribe function.
    return navigateRequester.receive(async ({ payload }) => {
      if (typeof payload === 'object') nav(payload.path, payload.options);
      // @ts-expect-error
      else nav(payload);
    });
  }, [nav]);

  return null;
}

// the callback return nothing so it should be undefined.
const result = await navigateRequester.send("/")
  1. createNotificationEmitter

It is similar to createRequestEmitter, but it's receive method returns an empty Promise and it can has many subscribers.

  1. mergeReceiver

Wrap many unsubscribe functions into one.

const notifier = createNotificationEmitter<{ name: string }>({ name: 'notification' });
const unsub = mergeReceiver(
    notifier.receive(async () => {}),
    notifier.receive(async () => {})
)
0.4.3

3 months ago

0.4.1

4 months ago

0.4.2

4 months ago

0.4.0

4 months ago

0.3.0

4 months ago

0.2.2

5 months ago