Flowable讀取文字檔案
阿新 • • 發佈:2019-01-02
public void readText() { final TextView textView = (TextView) findViewById(R.id.textView); final File directory = Environment.getExternalStorageDirectory(); final StringBuffer sb = new StringBuffer(); Flowable .create(new FlowableOnSubscribe<String>() { @Override public void subscribe(FlowableEmitter<String> e) throws Exception { try { FileReader reader = new FileReader(directory + "/haha.pdf"); BufferedReader br = new BufferedReader(reader); String str; while ((str = br.readLine()) != null && !e.isCancelled()) { while (e.requested() == 0) { if (e.isCancelled()) { break; } } e.onNext(str); } br.close(); reader.close(); e.onComplete(); } catch (Exception err) { e.onError(err); } } }, BackpressureStrategy.ERROR) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onSubscribe(Subscription s) { mSubscription = s; s.request(1); } @Override public void onNext(String s) { sb.append(s); mSubscription.request(1); } @Override public void onError(Throwable t) { } @Override public void onComplete() { textView.setText(sb); } }); }