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文件在后台线程中并在主线程中获取值。
答案 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() {
}
});