Completable.fromAction 没有执行 rjava2 中的代码
Completable.fromAction not executing the code in rjava2
Completable.fromAction(() -> startRecording())
.subscribeOn(Schedulers.io())
.subscribe(() -> {
boolean startSuccess = mMediaRecorder.getState() == MediaRecorder.RECORDING_STATE;
if (startSuccess) {
updateView();
startRepeatingTask();
}
},throwable -> {
Logger.info("Record failed with exception" + throwable);
}).dispose();
我正在尝试使用 Completable.fromAction 在后台执行代码,但如果我使用 subscribeOn(Schedulers.io()).
它不会执行代码
如果我删除 subscribeOn(Schedulers.io()),它会在主线程中执行代码。我想在后台线程中执行代码。
将 .fromAction
更改为 .fromCallable
可调用对象旨在执行单个发射器,然后完成。实际文档解释 here.
.fromAction
有点不同。文档 here.
人们已经在评论中强调了您的代码存在的问题 - 您立即在 Disposable
上调用 dispose()
,然后立即调用 Completable
returns。这意味着您甚至在 Completable
开始之前就取消了它。更改您的代码以将 Disposable
存储在实例变量中,并且仅当您不再有兴趣接收它完成时才调用 dispose()
。这通常发生在像 onPause
或 onStop
这样的生命周期回调中。例如:
public class SomeActivity extends Activity {
private final CompositeDisposable disposables = new CompositeDisposable();
//...
disposables.add(Completable.fromAction(() -> startRecording())
.subscribeOn(Schedulers.io()) //Note: `updateView` implies UI work. Should you also have `observeOn(AndroidSchedulers.mainThread)?
.subscribe(() -> {
boolean startSuccess = mMediaRecorder.getState() == MediaRecorder.RECORDING_STATE;
if (startSuccess) {
updateView();
startRepeatingTask();
}
}, throwable -> {
Logger.info("Record failed with exception" + throwable);
}));
//Later, in some other lifeycle callback when you no longer care about updates...
disposables.clear();
Completable.fromAction(() -> startRecording())
.subscribeOn(Schedulers.io())
.subscribe(() -> {
boolean startSuccess = mMediaRecorder.getState() == MediaRecorder.RECORDING_STATE;
if (startSuccess) {
updateView();
startRepeatingTask();
}
},throwable -> {
Logger.info("Record failed with exception" + throwable);
}).dispose();
我正在尝试使用 Completable.fromAction 在后台执行代码,但如果我使用 subscribeOn(Schedulers.io()).
它不会执行代码如果我删除 subscribeOn(Schedulers.io()),它会在主线程中执行代码。我想在后台线程中执行代码。
将 .fromAction
更改为 .fromCallable
可调用对象旨在执行单个发射器,然后完成。实际文档解释 here.
.fromAction
有点不同。文档 here.
人们已经在评论中强调了您的代码存在的问题 - 您立即在 Disposable
上调用 dispose()
,然后立即调用 Completable
returns。这意味着您甚至在 Completable
开始之前就取消了它。更改您的代码以将 Disposable
存储在实例变量中,并且仅当您不再有兴趣接收它完成时才调用 dispose()
。这通常发生在像 onPause
或 onStop
这样的生命周期回调中。例如:
public class SomeActivity extends Activity {
private final CompositeDisposable disposables = new CompositeDisposable();
//...
disposables.add(Completable.fromAction(() -> startRecording())
.subscribeOn(Schedulers.io()) //Note: `updateView` implies UI work. Should you also have `observeOn(AndroidSchedulers.mainThread)?
.subscribe(() -> {
boolean startSuccess = mMediaRecorder.getState() == MediaRecorder.RECORDING_STATE;
if (startSuccess) {
updateView();
startRepeatingTask();
}
}, throwable -> {
Logger.info("Record failed with exception" + throwable);
}));
//Later, in some other lifeycle callback when you no longer care about updates...
disposables.clear();