Can an effect in ngrx not subscribe to actions observable?

762 Views Asked by At

I've have a simple angular 10 service that expose a webSocketSubject, see the following code :


@Injectable({
  providedIn: 'root'
})
export class WebsocketService implements OnDestroy {
  private webSocketSubj : WebSocketSubject<User> //| Observable<Error>

  constructor() {
    this.webSocketSubj = webSocket("<some_url>")
    

  }

  ngOnDestroy(): void {
    this.webSocketSubj.complete()
  }

  getWebSocketSubject(): WebSocketSubject<User> {
    return this.webSocketSubj
  }

}

then I inject my service into an effect, that dispatch an update action every time new data are available on the websocket. To achieve this I don't need to subscribe to the actions observable. Here some sample code :


@Injectable()
export class EffectEffects {

  effect = createEffect(
     // Next line subscribe to my websocket subject, but not to the actions
    () => this.service.getWebSocketSubject().pipe(
        map(user => {
          return { type: '[Actions] Load Actionss Success', ...user }
        })
      )

  )

  constructor(private actions$: Actions, private service: WebsocketServiceService) {
  }

}

The code seems to work just fine, but my understanding of effect is that they must listen to every action and dispatch another action, like in this example.

So can someone explain me if there's some issue or drawback with my code ?

Thanks in advance for every tips, I just wish to get a full understanding of ngrx and rxjs.

1

There are 1 best solutions below

2
On BEST ANSWER

While you can use a side effect this way, I'd argue that it's not the correct pattern. Side effects are simply things that are supposed to happen when an action is dispatched that are not interactions with the state. They are, by definition, side effects of actions.

I'd say that the behaviour you are creating here should really be implemented in a service, as it is not triggered by an action. Your service would subscribe to the WebSocket, and then dispatch actions every time the socket emits.