skip to Main Content

I have an async stream provider (details omitted for clarity – basically it delivers a stream of Strings):

final mqttStreamProvider = StreamProvider<String>((ref) async* {
  final wsClient = ref.watch(mqttClientProvider.future);
  final service = await wsClient;

  await for (final value in service.getMessageStream()) {
    yield value;
  }
});

My understanding is that the right way to handle messages that don’t result in a UI impact (no rebuild) is to use :
ref.listen(...)
in the build method of the top level widget of my application.

However, I can’t find any example on how to listen to an async stream provider.
Any help on how to do this much appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    Well, just after asking the answer came :-)

    ref.listen(mqttStreamProvider, (prev, next) {
          print("new stream value $next");
        });
    

  2. You can watch for your StreamProvider inside the build method

    final steamAsync = ref.watch(mqttStreamProvider);
    

    and then you can use AsyncValue.when like this,

    return Scaffold(
      body: steamAsync.when(
        data: (data) {
          // return widget with data
        }
        error: (err, s) {
          // return error widget
        }
        loading: () {
          // return loading widget
        }
      ),
    );
    

    I believe that in this way you can handle your error and loading state easily.

    Also, you can skip loading or error using,

    steamAsync.when(
      skipError: true,
      skipLoadingOnRefresh: true,
      skipLoadingOnReload: true,
      .
      .
      .
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search