ReactiveX and Dart

Issue

I have a class Too

class Too{
 bool isLogged = false;
 BehaviorSubject suject = BehaviorSubject<bool>();

 Too({required this.isLogged}){
   suject = new BehaviorSubject<bool>.seeded(isLogged);
 }

void login(){
  isLogged = true;
  suject.sink.add(isLogged);
}

void logOut(){
  isLogged = false;
  suject.sink.add(isLogged);
}
void dispose(){
  suject.close();
}

and I also have the Foo class:

class Foo{
  Too _too = new Too(isLogged: false);
  
 _too.stream.listen((event) { print('${event}');});
}

My issue is When the user is calling the login() method of the Too class nothing happens at the level of the Foo class.

What I want to do is that if the user calls the login() method of the Too class and his isLogged attribute is set to true, then this change is done at the level of all the classes that have an attribute of the Too type.

Note: It’s much easier to do it with Angular or Ionic using RxJS, but with dart, I don’t know how to implement this mechanism.

Solution

Foo is not reacting because its listening to a different instance of Too.

The way you have it is that each new instance of Foo creates a new instance of Too. If I understand you correctly, you want all instances of Foo to react to any change to a single instance of Too.

You can use a singleton for this.

class Too {
  // one of a few ways to make a singleton in Dart
  Too._();
  static final _instance = Too._();
  factory Too() {
    return _instance;
  }

  final subject = BehaviorSubject<bool>.seeded(isLogged);

  static bool isLogged = false;

  void login() {
    isLogged = true;
    subject.sink.add(isLogged);
  }

  void logOut() {
    isLogged = false;
    subject.sink.add(isLogged);
  }

  void dispose() {
    subject.close();
  }
}

Now you can have any Foo object listen to the same Too instance.

class Foo {
  Foo() {
    Too().subject.stream.listen((event) {
      print('foo $event'); // this will now print whenever a subject from your Too class is updated. 
    });
  }
}

Now for example you could test this by creating a button with this as the onPressed.

onPressed: () {
 final foo = Foo(); // just created an example of a Foo object that will 
 // print the updated value of the Too singleton
 Too().login();
},

RxDart is great. However when it comes to reactive programming in Flutter, I suggest checking out Get X as it simplifies a lot of stream based stuff.

Answered By – Loren.A

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *