Skip to content

Streams

siva edited this page Dec 26, 2021 · 3 revisions

Stream

A server-streaming RPC is similar to a unary RPC, except that the server returns a stream of messages in response to a client’s request

Subscribing

For listening to a Stream, a subscribe call needs to take place. Only using the subscriptionId returned by the subscribe call, we can listen to the Streams

final subscribeResponse = await streamClient.subscribe(
  SubscribeRequest(dataStreamType: DataStreamType.STOCK_PRICES),
  options: sessionOptions(sessionId),
);
// Check if subscribe call is successful...
final pricesStream = streamClient.getStockPricesUpdates(
  subscribeResponse.subscriptionId,
  options: sessionOptions(sessionId),
);
pricesStream.listen((value) {/*Do your shit...*/});

Using a Stream

TBD

Unsubscribing

When we do not need to use a stream anymore, we need to unsubscribe from it using its subscribptionId

streamClient.unsubscribe(
  UnsubscribeRequest(subscriptionId: subId),
  options: sessionOptions(sessionId),
);

Global Streams

Streams that are required in multiple places in the app:

  • StockPricesUpdates
  • TransactionUpdates
  • NotificationUpdates
  • GamestateUpdates
    ...

All these streams along with stockListMap and subscriptionIds are stored in GlobalStreams class from global_streams.dart

Subscribing to Global Streams

  • Subscriptions to all the global streams need to be done after the user logs in. Use subscribeToGlobalStreams function from global_streams.dart for that
  • If any of the subscribe calls fail, the function will throw an exception. The exception must be handled
  • All the subscription ids we get will be stored in subscriptionIds, to be used later when unsubscribing
    • Should not need to use subscriptionIds anywhere else

Important: Do not forget to add any subscriptionId to subscriptionIds list. Then it cannot be unsubscribed at the end

Accessing Global Streams

After successfully subscribing to all the global streams, the GlobalStreams object must be registered in getIt. It is done at the root DalalBloc bloc listener.

final gameStateStream = getIt<GlobalStreams>().gameStateStream;
// Do your shit...

Unsubscribing from Global Streams

There are two cases when we have to unsubscribe from global streams:

  • When the user logs out
  • When the user is logged in but closes the app

Call the unsubscribeFromGlobalStreams function from global_streams.dart

  • It iterates over subscriptionIds and unsubscribes all of them
    • No need to await these calls. There is no data in the response
  • ...can't really do anything if any of the unsubscribe calls fail

Important: Always reset getIt after logout, reset method will unregister all the objects

Local Streams

TBD