-4

I am trying to make use an existing class which returns the data in the form of callback. The call is like this-

class Validator{
  validate(){
     DataProvider.getInstance(new DataListener(){
       @Override
       void onDataReady(String data){
          //Do something with data
       }
   });
  }

return //data when the above call is finished
}

I want a clean way to return the data which should be returned when the async call is completed. Putting a while loop and checking for data is an obvious but un-clean way. Can I achieve this using RxJava?

Note: It's ok for the validate function to wait if the call takes time

  • Rx java will be a good choice for these operation's – Anmol Dec 17 '18 at 13:46
  • @Anmol Can you please explain how? And why negative vote? Aren't we encourage new members to participate in the community? – Just Another Developer Dec 17 '18 at 13:47
  • 8
    yes but we also encourage all members to do some research before asking questions – Tim Dec 17 '18 at 13:49
  • @TimCastelijns How, by downvoting? And how are you sure that I did not do research? – Just Another Developer Dec 17 '18 at 13:54
  • 2
    yes, by downvoting. Downvoting a question that shows no research effort discourages people from asking such questions. You can take it personal and be offended by it, or you can consider it feedback, and improve your question – Tim Dec 17 '18 at 13:58
  • 2
    We aren't. But if you've not shown efforts of research in the post, some people take it as laziness. But literally, the hover text of the down arrow says *shows no research effort* – OneCricketeer Dec 17 '18 at 13:58

2 Answers2

1

Personally, RxJava is overkill. All you need is to pass in the continuation function as a parameter

class Validator {
    void validate(DataListener dl){
        DataProvider.getInstance(dl);
    }

And now, wherever you call this method, put in your new DataListener. Don't assign a result of validate() to a variable

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

Another possible solution if you don't want to use RxJava and if you want to just return a value from the validate method then you can just do it by creating an interface:

public interface ResultsListener{

  public void onResult(String data);
  public void onFailed();

}

public void validate(ResultListener callback){
     DataProvider.getInstance(new DataListener(){
       @Override
       void onDataReady(String data){
          //Do something with data
          callback.onResult(data);
       }
   });
  }

And when you make the call to validate() you can just do the following:

    validate(new ResultsListener() {
      @override
      void onResult(String valid) {
        // Do something with the returned data
      }

      @override
      void onFailed() {
        // something failed
      }

   });

Hopefully this helps!

AvidRP
  • 373
  • 2
  • 11