skip to Main Content

i want make get request after the first one finished because i need to send data from the response of first request with the body of second request to the server .. how i do this with getx

thanks

class ProductsController extends GetxController with StateMixin<Posts> {

  @override
  void onInit() {
    getData();
    super.onInit();
  }

  getData() async {
    try {
      change(null, status: RxStatus.loading());
      await postsApiProvider
          .getPosts()
          .then((value) {
      
        change(value, status: RxStatus.success());
      });
    } catch (exception) {
      change(null, status: RxStatus.error(exception.toString()));
    }
  }

  // i want this function fire after getData() 
  _getRelated() async {
    try {
      await postsApiProvider
          .getRelated(
            price: value.region  ----> because i need access to getDate values 
           )
          .then((value) {
      
      });
    } catch (e) {
      debugPrint(e.toString());
    }
  }
}

I tried that method but it didn’t work :

  @override
  void onReady() {
    _getRelated();
    super.onReady();
  }

2

Answers


  1. try using try with finally e.g

     //a sample model which is have data
     final Rx<MyModel> model = Model().obs;
     @override
      void onInit() {
       myFunctiontocall();
        super.onInit();
      }
     
     myFunctiontocall() async{
    
       try{
        // from the first function
        // make a function that will have data to the model
        myFirstFunctionToRun();
       }finally{
        // from done process in the above next is the finally
        // which next to be run
        // call the second function but make sure the model
        // have data
        thenFinallymySecondFunctiontoRun();
       }
    
      }
    
    Login or Signup to reply.
  2. You can achieve your result by using finally. But I would suggest creating a function for that, so that in future if you want to add one more function based on second function’s callback then you can easily achieve it.

    Here’s the example:

    gloablfun()async{
     await getData();
     await _getRelated();
    }
    

    then you can call the global function in the onInit method:

     @override
      void onInit() {
        gloablfun();
        super.onInit();
      }
    

    By using this way, you can add more functions in the future and your code will look cleaner than before.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search