# Dispatcher

There are cases when states of not related components, which has different places in state tree, should change *e.g:* *when list item is selected filter should collapse.* This is where dispatcher kicks in. Dispatcher is design to send and receive messages between components.

First create a message

```typescript
export class UpdateMessage extends Message {
  constructor(payload?: any) {
    super('MessageName', payload);
  }
}
```

### Publish message

and **publish** message from **B** component

```typescript
Dispatcher.publish(new UpdateMessage('payload'));
// or
Dispatcher.publish('UPDATE_MESSAGE', 'payload');
```

### Receive message

Then in **A** component **subscribe** to dispatcher like this:

```typescript
Dispatcher.subscribe(UpdateMessage as any, (payload: any) => {
    this.actions.update....
});

// or

Dispatcher.subscribe('UPDATE_MESSAGE', (payload: any) => {
  this.actions.update....
});
```

or you can **listen** for messages in **A** component like this:

```typescript
Dispatcher.listenTo<OptionalPayloadType>(UpdateMessage as any)
    .pipe(takeUntil(this.unsubscriber))
    .subscribe((payload: any) => {
        ...
    });

// or 

Dispatcher.listenTo<OptionalPayloadType>('UPDATE_MESSAGE')
    .pipe(takeUntil(this.unsubscriber))
    .subscribe((payload: any) => {
        ...
    });
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://vytautaspranskunas.gitbook.io/react-state-rxjs/core-concepts/dispatcher.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
