subscribe static method

Stream subscribe(
  1. String uri,
  2. String contract
)

Make a SUBSCRIPTION request for a resource. uri must include "suunto://" prefix and device serial if needed. contract must be a json string.

This call returns a Stream which will emit the notification data. Unsubscribing the Stream will automatically unsubscribe from the subscription.

Implementation

static Stream<dynamic> subscribe(String uri, String contract) {
  final controller = StreamController<dynamic>();

  final int subscriptionId =
      MdsImpl().subscribe(uri, contract, (errormsg, status) {
    // OnSuccess
  }, (errormsg, status) {
    // OnError
    debugPrint("onSubscriptionError: $status, msg: $errormsg");
    controller.addError(MdsError(status, errormsg));
  }, (data) {
    // onNotification
    final content = jsonDecode(data);
    controller.add(content);
  }, (errormsg, status) {
    // onSubscriptionError
    debugPrint("onSubscriptionError: $status, msg: $errormsg");
    controller.addError(MdsError(status, errormsg));
  });
  // Register onCancel handler now that we have subscriptionId
  controller.onCancel = () {
    MdsImpl().unsubscribe(subscriptionId);
    controller.close();
  };

  return controller.stream;
}