2

I would like to make the below functionality synchronous. The "onDataLoaded" needs to be called once the stream has been read completely. Please suggest what changes needs to be done.

String JsonContent="";

new HttpClient().getUrl(Uri.parse(uri))
  .then((HttpClientRequest request) 
   {
      request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);          
      return request.close();
   })
  .then((HttpClientResponse response) 
   {   
      response.transform(UTF8.decoder).listen((contents) {
        JsonContent = contents.toString();  
        print(JsonContent);
        //onDataLoaded(JsonContent); 
      });          
   });
Pixel Elephant
  • 20,649
  • 9
  • 66
  • 83
Sudhi
  • 229
  • 3
  • 4
  • 13

1 Answers1

3

this should work

import 'dart:io';
import 'dart:convert' show UTF8;

void main(args) {
String JsonContent="";

new HttpClient().getUrl(Uri.parse(uri))
  .then((HttpClientRequest request)
   {
      request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
      return request.close();
   })
  .then((HttpClientResponse response)
   {
      response.transform(UTF8.decoder).listen((contents) {
        JsonContent = contents.toString();
        print(JsonContent);
        //onDataLoaded(JsonContent);
      }, onDone: () => onDataLoaded(JsonContent));
   });

}

void onDataLoaded(String jsonContent) {
  print(jsonContent);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Is there a way to let onDataLoaded execute first before terminating from the main(args). – Sudhi May 22 '14 at 17:16
  • I saw that in your question but wasn't sure if you really meant it because the other part said you want to call `onDataLoaded` when retrieving is done. No, I haven't found a sync version of `getUrl` for the server. The client has `request.open("GET", url, async : false);` See also http://stackoverflow.com/questions/18404489 – Günter Zöchbauer May 22 '14 at 17:19
  • Tried that piece of code before posting my query. Same behaviour - main() terminates and then the content is printed. – Sudhi May 22 '14 at 17:24
  • Async execution is putting the closure in the event queue and when the current thread of execution (main) is done, the next item in the queue (getUrl) is executed. – Günter Zöchbauer May 22 '14 at 17:26