Ionic App is crashing with Ngrx and ngx-socket-io

279 views Asked by At

I'm working in an Ionic App with angular and socket IO (also I'm using ngrx), but I have a problem that the socket stops when the screen is inactive.

The fail process is this:

  1. First you enter the app, so the socket connects. The socket connects only if my redux state has a token, in other case, the socket will not has to connect
  2. Then, imagine that you left the app executing and your phone automatically locks the screen, so the app changes to an "pause" state
  3. After 10 minutes on the pause state, you unlock your phone which causes that the app enter in a resume state and then is when the socket makes crash the whole app an it simply closes

The socket works correctly

I know is the socket becouse I tried removing just some lines of my socket service and the app are not closing. If I just wait 7 or 8 or 5 minutes or less to unlock the phone, the app won't crash. The crash only happens after 10 minutes with the screen locked

This is my ngx-socket-io configuration

  const config: SocketIoConfig = { url: 'http://localhost:5000', options: { transports: ["websocket", "xhr-polling", "jsonp-polling"], autoConnect: false } };

  @NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
      BrowserModule,
      HttpClientModule,
      IonicModule.forRoot(),
      AppRoutingModule,
      StoreModule.forRoot(appReducers),
      StoreDevtoolsModule.instrument({ maxAge: 25, logOnly: environment.production}),
      EffectsModule.forRoot(effectsArray),
      SocketIoModule.forRoot(config),

    ],
    providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ],
    bootstrap: [AppComponent],
  })
  export class AppModule {}

And this is my app.component.ts

  constructor(public store: Store<AppState>, public websocketService: WebsocketService, public appStatusService: AppStatusService, public platform: Platform) { }

  ngOnInit() {
      this.store.select('session').pipe(filter(session => session !== null)).subscribe(session => {
          // IF I REMOVE THIS CONDITION, THE APP WON'T CRASH
          if (session.currentSession.token === null) { 
            // DISCONNECT IF WAS CONNECTED
            this.websocketService.disconnectSocket();  
          } else { 
            // CONNECT                                
            this.websocketService.connectSocket();     
          }
      });

      this.initializeApp();
  }

  initializeApp() {
      this.platform.ready().then(() => {
        this.platform.pause.subscribe(e => { this.appStatusService.setStatus(false); });
        this.platform.resume.subscribe(e => { this.appStatusService.setStatus(true); });
      });
  
  }

This is my webSocket Service

export class WebsocketService {

  socketConnected = false;
  socketStatus:boolean;


  constructor(private socket: Socket,  public http: HttpClient, public apiConfigService: ApiConfigService, public authService: AuthService, public platform: Platform) { 
      this.checkStatus();
  }

  async connectSocket() {
      const data = await this.socketCredentials();
      if (data !== null && data !== undefined) {
          this.socket.ioSocket.io.opts.query = { sessionUUID: data.sessionUUID, channelUUID: data.channelUUID } ;
          this.socketConnected = true;
          this.socket.connect();
          this.socket.emit( 'JOIN_ROOM', {channelID: data.channelUUID  } );
      }
  }


  disconnectSocket() {
      if (this.socketConnected === true) { this.socket.disconnect(); this.socketConnected = false;  }
  }


  checkStatus() {
      this.socket.on('connect', () => { console.log('SOCKET CONNECTED');  });
      this.socket.on('disconnect', () => { console.log('SOCKET DISCONNECTED'); });
  }



  socketCredentials(): Promise<any> {
      // I need to get some credentials to connect the socket. Only can connect to my server if I have this credentials
      return new Promise(resolve => {
      this.http.get('http://localhost:3000/socket/auth').toPromise().then(response => { resolve(response); });
      });
  }

}
0

There are 0 answers