Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 48983

Replace latching flag with observable

$
0
0

I have a bluetooth-le connection to a device that occasionally drops. When this happens I try to reconnect. The user can also choose to disconnect. I need to differentiate between these events.

  return this.ble.connect(macAddress, this.onDisconnect.bind(this))
        .then(connection => this.commsData.broadcastConnection(macAddress))

communications data service

  private _connection$: Subject<IConnectionEvent> = new Subject();
  public get connection$(): Observable<IConnectionEvent> {
    return this._connection$.asObservable();
  }
  public broadcastConnection(macAddress: string) {
    this._connection$.next({event: ConnectionEvent.CONNECT, macAddress});
  }
  public broadcastDisconnection(connectionEvent: ConnectionEvent) {
    this._connection$.next({event: connectionEvent});
  }

The bluetooth-le connect method takes an onDisconnect callback that fires in both situations. I have a subject that returns observables emitting connection states as they change. A connection emits ‘connect’, a manual disconnection emits ‘disconnect’ and I need a way to signal a dropped connection.

  private isExpectedDisconnection: boolean = false;

  onDisconnect(macAddress: string) {
    // default behaviour is to retry connection
    if (!this.isExpectedDisconnection) {
      return this.commsData.broadcastDisconnection(ConnectionEvent.DROP);
    }
    this.isExpectedDisconnection = false;
  }

I’ve achieved this with a flag, ‘isExpectedDisconnection’, which is set false by default, true when a user disconnection occurs and reset to false in the onDisconnect callback function. This is a really imperative way of doing something I feel should be handled reactively. But I’m still having a hard time thinking that way.

  this.commsData.connection$
    .subscribe({
      next: (connectionEvent: IConnectionEvent) => {
        if (!connectionEvent) return;

        if (connectionEvent.event === ConnectionEvent.CONNECT) return;

        if (connectionEvent.event === ConnectionEvent.DISCONNECT) {
          this.isExpectedDisconnection = true;
          return this.ble.disconnect(this.macAddress);
        }

        if (connectionEvent.event === ConnectionEvent.DROP) {
          return this.connect(this.macAddress);
        }
      }
    })

connection event

  export enum ConnectionEvent {
    CONNECT = 'connected',
    DISCONNECT = 'disconnected',
    DROP = 'dropped'
  }

How can (or should) I have another observable merged with connection$ and only act if the disconnect was unexpected?

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 48983

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>