1

Let Two Stream deliver two different types of data. I want a one stream from those two stream that combine the data and wrap in data class and delivers it.

Example:

Stream<String> stream1;
Stream<String> stream2;

class Data{
    String s1;
    String s2;
    Data(this.s1,this.s2);
}
dkp1997
  • 175
  • 1
  • 2
  • 7

2 Answers2

1

There's no "out of the box" solution for this. You typically have to create custom logic for this (called StreamTransformer).

You can use 3rd party libraries on the other hand. Such as rxdart, which includes multiples stream fusions operators:

Stream<String> stream1;
Stream<String> stream2;
Stream<String> concat = Observable.combineLatest2(stream1, stream2, (a, b) => a + b);
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • 1
    and what about `StreamGroup`? i never used it but the docs seem to say that it is a stream multiplexer – pskink Jan 13 '19 at 15:17
  • Ah well, it's not shipped with dart SDK and requires all stream values to have the same type – Rémi Rousselet Jan 13 '19 at 15:22
  • 1
    ```StreamGroup.merge([stream1, stream1]).map((event) { //event will be of type Object if the type aren't the same return event; });``` – Paul Okeke Apr 12 '21 at 11:02
0

Use stream transform function combineLatest from the stream_transform package (add dependency to "stream_transform" in pubspec.yml).

import 'package:stream_transform/stream_transform.dart' show combineLatest;

Stream<Data> combinedStream(Stream<String> stream1, Stream<String> stream2) {
  return stream1.transform(combineLatest(stream2, (s1, s2) => Data(s1, s2)));
}

Also answered here: https://stackoverflow.com/a/55912217/3635696 (without telling how to access the combineLastest function).