从异步方法返回多个结果? [英] Return multiple results from an async method?

查看:109
本文介绍了从异步方法返回多个结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个看起来像这样的方法:

I currently have a method that looks something like this:

typedef void MyCallback(int status, String body);


void makeRequest(String url, MyCallback callback) async {
  if( someCondition ){
    callback(1, '');
  }

  Response response = await http.get(url);

  if( response.httpCode == 200 ){
    callback(2, response.body);
  }
  else{
    callback(3, '');
  }
}

我想摆脱回调,以便我可以等待 makeRequest 的结果。但是,如果我只是让它返回 Future ,我将不能返回多次。

I want to get rid of the callback so that I can wait for the result(s) of makeRequest. But if I simply make it return a Future, I won't be able to return more than once.

我研究了使用流,但是似乎有点复杂。因此,基本上,我正在寻找像 Future 一样方便的东西,但这可能会收到部分结果,即多次收到结果。为了说明:

I looked into using streams, but it seems a bit complicated. So basically I'm looking for something as convenient as a Future but that could receive "partial results", i.e. receive a result more than once. To illustrate:

MultiFuture<int> makeRequest(String url){
  MultiFuture result = new MultiFuture();

  if( someCondition ){
    result.value(1);
  }

  http.get(url).then((response){
    if( response.httpCode == 200 ){
      result.value(2);
    }
    else{
      result.value(3);
    }

    result.finish();
  });


  return result;
}




MultiFuture requestResult = makeRequest('https://example.com');

await requestResult.onValue((int value){
  print('value: $value');
});      
// When result.finish() is called, the await is finished

正在使用流是我的最佳选择,还是我不知道的某种 MultiFuture

Is using a stream my best option, or is there some kind of MultiFuture that I just don't know about?

推荐答案

从异步方法返回多个结果正是流的作用。这是我根据您的代码制作的一个示例,因此可以使您更容易理解它的工作原理:

Return multiple results from an async method is exactly what streams does. Here is an example I made based on your code so it could be easier for you to understand how it works:

class MultiFuture {
  StreamController<int> _resultController = StreamController<int>();
  Stream<int> get requestResult => _resultController.stream;

  void makeRequest(String request) async {
    if (true) {
      _resultController.sink.add(1);
    }

    // mock request
    await Future.delayed(Duration(seconds: 3));

    if (true) {
      _resultController.sink.add(2);
    } else {
      _resultController.sink.add(3);
    }
  }

  void example() {
    makeRequest("https://example.com");

    requestResult.listen((value) {
      print('value: $value');
    });
  }
}

您可以调用MultiFuture()。example( );

You can test it calling MultiFuture().example();

但是我建议您看这些简单的短片,以更好地了解:
使用Dart异步编码

But I recommend you to see these simple short videos to have a better idea: Async Coding With Dart

这篇关于从异步方法返回多个结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆