Home > Software design >  Dart Streams - Is it possible to map to a new async stream?
Dart Streams - Is it possible to map to a new async stream?

Time:12-07

I might be getting confused with dart streams and RX related frameworks here.

But just wanted to check, is it possible to map to a new async stream?

For example

apiService.signInStream returns Stream<signinResponse>

apiService.getUserDetailsStream returns Stream<userResponse>

So I want to make the sign in call, take the user id from it to get the user details.

I tried something like this...

apiService.signInStream(requestSignIn).asyncMap((event) => apiService.getUserDetailsStream(event.userId));

But that returns... Stream<Stream<userResponse>>

I'd like it to return <Stream<userResponse>

Do I have to listen within the map somehow?

Thanks

CodePudding user response:

You should listen:

apiService.signInStream(requestSignIn).listen((event) {
  apiService.getUserDetailsStream(event.userId)).listen((details) {
    // use event and details here
  });
});

CodePudding user response:

There are many approaches and I cannot say which one you may use because I have no context of your project, all I have here are simply Streams.

Lets begin:

But that returns... Stream<Stream<userResponse>>

This is what return because this is what it is, you are iterating over a stream and returning another stream, streams are like lists, but asynchronous. Why do you want to ignore the userResponse stream? is this really a Stream? Why do not use a simply Future instead if you want just the returned data?

And since you're mapping the signInStream, I'll consider you:

  • Wanna map each signInStream event
  • Want just the first element of the getUserDetailsStream.
// What you have right now is:
final itIsWhatYouAreDoing = signInStream().asyncMap((event) => getUserDetailsStream());

// What you are saying you want to achieve:
final userDetailsStream = signInStream().asyncMap((event) async => await getUserDetailsStream().first);

print(itIsWhatYouAreDoing); // Stream<Stream<int>>
print(userDetailsStream); // Stream<int>

But this has some cons: you lose any other post-event emitted by all [getUserDetailsStream] Streams.

You didn't provide any detail about this, so I'll assuming they are irrelevant?!?

  • Related