3

我有一个DownloadsService使用dio包处理文件下载的类。我想听听我的班级的下载进度,该班级在我的ViewModel班级中实现了该downloadFile方法DownloadService。我该怎么做呢?

这是我的课程代码片段DownloadsService

class DownloadsService {
   final String urlOfFileToDownload = 'http://justadummyurl.com/'; //in my actual app, this is user input
   final String filename = 'dummyfile.jpg';
   final String dir = 'downloads/$filename'; //i'll have it saved inside internal storage downloads directory

   void downloadFile() {
     Dio dio = Dio();
     dio.download(urlOfFileToDownload, '$dir/$filename', onReceiveProgress(received, total) {
        int percentage = ((received / total) * 100).floor(); //this is what I want to listen to from my ViewModel class
     });
   }
}

这是我的ViewModel课:

class ViewModel {
   DownloadsService _dlService = DownloadsService(); //note: I'm using get_it package for my services class to make a singleton instance. I just wrote it this way here for simplicity..

      void implementDownload() {

       if(Permission.storage.request().isGranted) { //so I can save the file in my internal storage
          _dlService.downloadFile();

        /*
         now this is where I'm stuck.. My ViewModel class is connected to my View - which displays
         the progress of my download in a LinearProgressIndicator. I need to listen to the changes in
         percentage inside this class.. Note: my View class has no access to DownloadsService class. 
       */

      }        
   }
}

Dio 文档提供了如何将响应类型转换为流/字节的示例。但它没有提供任何示例说明如何在下载文件时执行此操作。有人能指出我正确的方向吗?我现在真的被困住了..非常感谢!

4

1 回答 1

1

如果View创建ViewModel,则必须在View类中定义PublishSubject变量,然后将其传递给ViewModel,并将其作为参数传递给DownloadsService

像这样 :

class ViewModel {
       PublishSubject publishSubject;
       ViewModel(this.publishSubject);
       DownloadsService _dlService = DownloadsService();   
          void implementDownload() { 
           if(Permission.storage.request().isGranted) {  
              _dlService.downloadFile(publishSubject); 
          }        
       }
    }

以便View在downloadFile方法之前侦听将发生的更改,然后依次发送更改

像这样:

void downloadFile(PublishSubject publishSubject) {
     Dio dio = Dio();
     dio.download(urlOfFileToDownload, '$dir/$filename', 
        onReceiveProgress(received,total) {
        int percentage = ((received / total) * 100).floor(); 
        publishSubject.add(percentage);
     });
   }

让界面监听到之前会发生的变化

像这样:

class View {
  PublishSubject publishSubject = PublishSubject();
  ViewModel viewModel;
  View(){
    publishSubject.listen((value) {
      // the value is percentage.
      //can you refresh view or do anything
    });
   viewModel = ViewModel(publishSubject);
  }  
}
于 2020-06-14T22:07:56.790 回答