暫無描述

RNFetchBlobDefaultResp.java 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package com.RNFetchBlob.Response;
  2. import com.RNFetchBlob.RNFetchBlobConst;
  3. import com.RNFetchBlob.RNFetchBlobProgressConfig;
  4. import com.RNFetchBlob.RNFetchBlobReq;
  5. import com.facebook.react.bridge.Arguments;
  6. import com.facebook.react.bridge.ReactApplicationContext;
  7. import com.facebook.react.bridge.WritableMap;
  8. import com.facebook.react.modules.core.DeviceEventManagerModule;
  9. import java.io.IOException;
  10. import okhttp3.MediaType;
  11. import okhttp3.ResponseBody;
  12. import okio.Buffer;
  13. import okio.BufferedSource;
  14. import okio.Okio;
  15. import okio.Source;
  16. import okio.Timeout;
  17. /**
  18. * Created by wkh237 on 2016/7/11.
  19. */
  20. public class RNFetchBlobDefaultResp extends ResponseBody {
  21. String mTaskId;
  22. ReactApplicationContext rctContext;
  23. ResponseBody originalBody;
  24. public RNFetchBlobDefaultResp(ReactApplicationContext ctx, String taskId, ResponseBody body) {
  25. this.rctContext = ctx;
  26. this.mTaskId = taskId;
  27. this.originalBody = body;
  28. }
  29. @Override
  30. public MediaType contentType() {
  31. return originalBody.contentType();
  32. }
  33. @Override
  34. public long contentLength() {
  35. return originalBody.contentLength();
  36. }
  37. @Override
  38. public BufferedSource source() {
  39. return Okio.buffer(new ProgressReportingSource(originalBody.source()));
  40. }
  41. private class ProgressReportingSource implements Source {
  42. BufferedSource mOriginalSource;
  43. long bytesRead = 0;
  44. ProgressReportingSource(BufferedSource originalSource) {
  45. mOriginalSource = originalSource;
  46. }
  47. @Override
  48. public long read(Buffer sink, long byteCount) throws IOException {
  49. long read = mOriginalSource.read(sink, byteCount);
  50. bytesRead += read > 0 ? read : 0;
  51. RNFetchBlobProgressConfig reportConfig = RNFetchBlobReq.getReportProgress(mTaskId);
  52. if(reportConfig != null && reportConfig.shouldReport()) {
  53. reportConfig.tick(bytesRead/contentLength());
  54. WritableMap args = Arguments.createMap();
  55. args.putString("taskId", mTaskId);
  56. args.putString("written", String.valueOf(bytesRead));
  57. args.putString("total", String.valueOf(contentLength()));
  58. rctContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  59. .emit(RNFetchBlobConst.EVENT_PROGRESS, args);
  60. }
  61. return read;
  62. }
  63. @Override
  64. public Timeout timeout() {
  65. return null;
  66. }
  67. @Override
  68. public void close() throws IOException {
  69. }
  70. }
  71. }