如何在后台线程中使用RX从android中的资产文件夹读取文件

时间:2019-03-07 02:46:25

标签: android rx-java

private ModelObject model;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

    }

    private void readFile() {
        if (model == null) {
            Gson gson = new Gson();
            final String helpItem = “my _file.json”;
            InputStream stream = null;
            try {
                stream = getResources().getAssets().open(helpItem);
                Reader reader = new InputStreamReader(stream);
                model = gson.fromJson(reader, ModelObjects.class);
                reader.close();
                stream.close();
            } catch (IOException e) {
                Timber.w(e);
            } finally {
                fileclose();
            }
        }
    }

这是我使用此代码的代码,我正在从Assets文件夹中读取文件并解析为Model对象,但我想在后台线程而不是Main线程中读取此文件,以便获取数据main线程,请建议我如何实现read文件在后台线程中并在主线程中获取值。

1 个答案:

答案 0 :(得分:2)

您可以使用Observable这样操作:

Observable.fromCallable(new Callable<ModelObject>() {
      @Override public ModelObject call() throws Exception {
        return readFile(); // Make readFile so that it returns ModelObject
      }
    })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<ModelObject>() {
          @Override public void onSubscribe(Disposable d) {

          }

          @Override public void onNext(ModelObject o) {

          }

          @Override public void onError(Throwable e) {

          }

          @Override public void onComplete() {

          }
        });