Home > OS >  How to subscribe to changes in another Controller with GetX?
How to subscribe to changes in another Controller with GetX?

Time:11-19

How do I get subscribe to changes from one GetxController inside another?

class HomeController extends GetxController {
    var home = '';
    String userName = '';
    refresh() async {
        //call http...
        update();
    }
}

class LoginController extends GetxController {
    String email = '';
    String password = '';

    onInit() {
        GetBuilder<HomeController>((_){
          email = _.userName;
        });
    }
}

Say I want LoginController to subscribe to changes when HomeController is updated. How do I do that?

I take it I can't use GetBuilder like above?

CodePudding user response:

You can use basically below codes;

  • userName field must be extend Rx object for the listenable stream.
onInit() {
    final mailSubs = Get.find<HomeController>.userName.stream.listen((event) {
      email = event;
    });
  }

CodePudding user response:

You should try below code might useful for you. Either you can listen for specific controller or listen the variable of the controller.

class LoginController extends GetxController {
  String email = '';
  String password = '';
  HomeController cnt = Get.find();

  @override
  onInit() {
    // Listen to the Controller
    cnt.obs.listen((value) {
      print(value);
    });
    // Listen to the username variable
    cnt.userName.obs.listen((value) {
      print(value);
    });
  }
}
  • Related