rxdart - using combineLatest, the way combiner works

1.3k Views Asked by At

How does the combiner actually work?

Stream<bool> get isValid => Rx.combineLatest2(name1, mobile1, (name2, mobile2) => true);

If name1 and mobile1 are streams, then what are the types of name2 and mobile2 in brackets?

1

There are 1 best solutions below

0
On BEST ANSWER

In your example, name2 and mobile2 refer to the latest content that was emitted by the streams name1 and mobile1. So your question - the types of name2 and mobile2 - depend on the streams that you give it.

I think calling them name1 and name2 actually kind of makes it a bit confusing, and perhaps it would make more sense to think of it like this:

Rx.combineLatest2(nameStream, mobileStream, (name, mobile) => ... )

To give a concrete example, imagine that name is a String and mobile is int. And imagine that what you want is a Stream of your own class called Person which has the parameter name and mobile like this:

class Person {
  String name;
  int mobile;
  
  Person({required this.name, required this.person});
}

You could combine your latest name and latest mobile to get a Stream<Person> like this:

Stream<Person> get person => 
   Rx.combineLatest2(
      nameStream, mobileStream, (name, mobile) => 
         Person(name: name, mobile: mobile));

where:

  • nameStream is of type Stream<String>
  • mobileStream is of type Stream<int>
  • name is of type String
  • mobile is of type int
  • and the get function person returns Stream<Person>

You can specify your class types in the function like this:

Stream<Person> get person => 
  Rx.combineLatest2<String, int, Person>(
    nameStream, mobileStream, (name, mobile) => 
       Person(name: name, mobile: mobile));