Skip to content

Commit

Permalink
Merge pull request #164 from GetStream/channel_and_notification_events
Browse files Browse the repository at this point in the history
fix: Add missing ngZone reenters
  • Loading branch information
szuperaz authored Dec 13, 2021
2 parents 35104a9 + d2995ac commit 8e05fd8
Show file tree
Hide file tree
Showing 8 changed files with 278 additions and 183 deletions.
77 changes: 77 additions & 0 deletions docusaurus/docs/Angular/concepts/change-detection.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
id: change-detection
sidebar_position: 4
title: Change detection
---

For performance reasons, the Stream chat WebSocket connection is opened outside of the [Angular change detection zone](https://angular.io/guide/zone). This means that when we react to WebSocket events, Angular won't update the UI in response to these events. Furthermore, if a new component is created reacting to a WebSocket event (for example, if we receive a new message, and a new message component is created to display the new message), the new component will operate outside of the Angular change detection zone. To solve this problem, we need to reenter Angular's change detection zone.

## Reentering Angular's change detection zone

You can reenter Angular's change detection zone with the `run` method of the `NgZone` service. For example if you want to display a notification when a user is added to a channel, you can watch for the `notification.added_to_channel` event and return to the zone when that event is received:

```typescript
import { Component, NgZone, OnInit } from "@angular/core";
import { filter } from "rxjs/operators";
import { ChatClientService, NotificationService } from "stream-chat-angular";

@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent implements OnInit {
constructor(
private chatService: ChatClientService,
private notificationService: NotificationService,
private ngZone: NgZone
) {}

ngOnInit(): void {
this.chatService.notification$
.pipe(filter((n) => n.eventType === "notification.added_to_channel"))
.subscribe((notification) => {
// reenter Angular's change detection zone
this.ngZone.run(() => {
this.notificationService.addTemporaryNotification(
`You've been added to the ${notification.event.channel?.name} channel`,
"success"
);
});
});
}
}
```

If you were to display the notification without reentering Angular's zone, the `addTemporaryNotification` would run outside of Angular's change detection zone, and the notification wouldn't disappear after the 5-second timeout.

## When necessary to reenter the zone

You need to reenter Angular's change detection zone when

- you subscribe to events using the [`notification$`](../services/chat-client.mdx/#notification) Observable of the `ChatClientService`
- you subscribe to channel events

For example the [`ChannelPreview`](../components/channel-preview.mdx) component needs to subscribe to the `message.read` channel events to know if the channel has unread messages and reenter Angular's zone when an event is received:

```typescript
this.channel.on("message.read", () =>
this.ngZone.run(() => {
this.isUnread = !!this.channel.countUnread() && this.canSendReadEvents;
})
);
```

## When unnecessary to reenter the zone

You **don't** need to reenter the zone when

- you use the SDK's default components in your UI and don't watch for additional events
- when you [override the default channel list behavior](../services/channel.mdx/#channels)
- when you subscribe to the [`connectionState$`](../services/chat-client.mdx/#connectionstate) Observable of the `ChatClientService`

If you are unsure whether or not you are in Angular's zone, you can use the following function call to check:

```typescript
NgZone.isInAngularZone();
```
10 changes: 8 additions & 2 deletions docusaurus/docs/Angular/services/channel.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ Queries the channels with the given filters, sorts and options. More info about

## channels$

Emits the currently loaded and [watched](https://getstream.io/chat/docs/javascript/watch_channel/?language=javascript) channel list. Apart from pagination, the channel list is also updated on the following events:
Emits the currently loaded and [watched](https://getstream.io/chat/docs/javascript/watch_channel/?language=javascript) channel list.

:::important
If you want to subscribe to channel events, you need to manually reenter Angular's change detection zone, our [Change detection guide](../concepts/change-detection.mdx) explains this in detail.
:::

Apart from pagination, the channel list is also updated on the following events:

| Event type | Default behavior | Custom handler to override |
| ----------------------------------- | ------------------------------------------------------------------ | --------------------------------------------- |
Expand All @@ -37,7 +43,7 @@ Our platform documentation covers the topic of [channel events](https://getstrea
Emits the currently active channel.

:::important
Please note that for performance reaasons the client is connected [outside of the NgZone](https://angular.io/guide/zone#ngzone-1), if you want to subscribe to [notification or channel events](https://getstream.io/chat/docs/javascript/event_object/?language=javascript), you will need to [reenter the NgZone](https://angular.io/guide/zone#ngzone-run-and-runoutsideofangular) or call change detection manually (you can use the [`ChangeDetectorRef`](https://angular.io/api/core/ChangeDetectorRef) or the [`ApplicationRef`](https://angular.io/api/core/ApplicationRef) for that).
If you want to subscribe to channel events, you need to manually reenter Angular's change detection zone, our [Change detection guide](../concepts/change-detection.mdx) explains this in detail.
:::

## setAsActiveChannel
Expand Down
10 changes: 5 additions & 5 deletions docusaurus/docs/Angular/services/chat-client.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ The `ChatClient` service connects the user to the Stream chat.

The [StreamChat client](https://github.com/GetStream/stream-chat-js/blob/master/src/client.ts) instance. In general you shouldn't need to access the client, but it's there if you want to use it.

:::important
Please note that for performance reaasons the client is connected [outside of the NgZone](https://angular.io/guide/zone#ngzone-1), if you want to subscribe to [notification or channel events](https://getstream.io/chat/docs/javascript/event_object/?language=javascript), you will need to [reenter the NgZone](https://angular.io/guide/zone#ngzone-run-and-runoutsideofangular) or call change detection manually (you can use the [`ChangeDetectorRef`](https://angular.io/api/core/ChangeDetectorRef) or the [`ApplicationRef`](https://angular.io/api/core/ApplicationRef) for that).
:::

## init

Creates a [`StreamChat`](https://github.com/GetStream/stream-chat-js/blob/668b3e5521339f4e14fc657834531b4c8bf8176b/src/client.ts#L124) instance using the provided `apiKey`, and connects a user with the given `userId` and `userToken`. More info about [connecting users](https://getstream.io/chat/docs/javascript/init_and_users/?language=javascript) can be found in the platform documentation.

## notification$

Emits [`Notification`](https://github.com/GetStream/stream-chat-angular/blob/master/projects/stream-chat-angular/src/lib/chat-client.service.ts) events, the list of [supported events](https://github.com/GetStream/stream-chat-angular/blob/master/projects/stream-chat-angular/src/lib/chat-client.service.ts) can be found on GitHub. The platform documentation covers [events in detail](https://getstream.io/chat/docs/javascript/event_object/?language=javascript).
Emits [`Notification`](https://github.com/GetStream/stream-chat-angular/blob/master/projects/stream-chat-angular/src/lib/chat-client.service.ts) events. The platform documentation covers [the list of client and notification events](https://getstream.io/chat/docs/javascript/event_object/?language=javascript).

:::important
For performance reasons this Observable operates outside of the Angular change detection zone. If you subscribe to it, you need to manually reenter Angular's change detection zone, our [Change detection guide](../concepts/change-detection.mdx) explains this in detail.
:::

## connectionState$

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { Component, Input, NgZone, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import {
Channel,
Expand All @@ -21,7 +21,7 @@ export class ChannelPreviewComponent implements OnInit, OnDestroy {
private subscriptions: (Subscription | { unsubscribe: () => void })[] = [];
private canSendReadEvents = true;

constructor(private channelService: ChannelService) {}
constructor(private channelService: ChannelService, private ngZone: NgZone) {}

ngOnInit(): void {
this.subscriptions.push(
Expand Down Expand Up @@ -51,11 +51,11 @@ export class ChannelPreviewComponent implements OnInit, OnDestroy {
this.channel!.on('channel.truncated', this.handleMessageEvent.bind(this))
);
this.subscriptions.push(
this.channel!.on(
'message.read',
() =>
(this.isUnread =
!!this.channel!.countUnread() && this.canSendReadEvents)
this.channel!.on('message.read', () =>
this.ngZone.run(() => {
this.isUnread =
!!this.channel!.countUnread() && this.canSendReadEvents;
})
)
);
}
Expand All @@ -81,19 +81,21 @@ export class ChannelPreviewComponent implements OnInit, OnDestroy {
}

private handleMessageEvent(event: Event) {
if (this.channel?.state.messages.length === 0) {
this.latestMessage = 'Nothing yet...';
return;
}
if (
!event.message ||
this.channel?.state.messages[this.channel?.state.messages.length - 1]
.id !== event.message.id
) {
return;
}
this.setLatestMessage(event.message);
this.isUnread = !!this.channel.countUnread() && this.canSendReadEvents;
this.ngZone.run(() => {
if (this.channel?.state.messages.length === 0) {
this.latestMessage = 'Nothing yet...';
return;
}
if (
!event.message ||
this.channel?.state.messages[this.channel?.state.messages.length - 1]
.id !== event.message.id
) {
return;
}
this.setLatestMessage(event.message);
this.isUnread = !!this.channel.countUnread() && this.canSendReadEvents;
});
}

private setLatestMessage(message?: FormatMessageResponse | MessageResponse) {
Expand Down
Loading

0 comments on commit 8e05fd8

Please sign in to comment.