1
在jQuery中,承諾的想法是做經:RxJava:是否有某種形式的鏈讓我「在繼續之前等待觀察結果A,B,C完成」?
var taskA = $.Deferred();
var taskB = $.Deferred();
var taskC = $.Deferred();
// Callback starts when all tasks are complete/resolved
$.when(taskA, taskB, taskC).done(function(results) {
var resultA = results[0];
var resultB = results[1];
var resultC = results[2];
// ...
});
// Fire off long tasks
longTask1(function(result) { taskA.resolve("result"); });
longTask2(function(result) { taskB.resolve("result"); });
longTask3(function(result) { taskC.resolve("result"); });
我覺得應該有一個RxJava但equivelant我不知道它的名字。
編輯:添加我的Android活動代碼澄清
/**
* What I expected to happen:
* - User has to click buttons A, B and C in order to pass.
*
* What actually happens
* - User clicks any button and passes.
*/
public class RxTestActivity extends AppCompatActivity {
PublishSubject<Boolean> subjectClickedA;
PublishSubject<Boolean> subjectClickedB;
PublishSubject<Boolean> subjectClickedC;
@Bind(R.id.btnA) Button btnA;
@Bind(R.id.btnB) Button btnB;
@Bind(R.id.btnC) Button btnC;
@Bind(R.id.labelTest) TextView txtSuccess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.bind(this);
subjectClickedA = PublishSubject.create();
subjectClickedB = PublishSubject.create();
subjectClickedC = PublishSubject.create();
// Create an observer which waits until all 3 tasks are complete before
// triggering it's own "onCompleted".
Observable.merge(subjectClickedA, subjectClickedB, subjectClickedC)
// Ensure all subjects are completed
// TODO: doesn't work
.all(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean aBoolean) {
// Won't let anything through until all of tasks are complete
return subjectClickedA.hasCompleted() && subjectClickedB.hasCompleted() && subjectClickedC.hasCompleted();
}
})
.subscribe(new Subscriber<Boolean>() {
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Boolean aBoolean) {
// aBoolean value comes in as false
Log.e("Subscriber onNext", String.valueOf(aBoolean));
}
@Override
public void onCompleted() {
// This triggers on the first button click (no matter which one)
// TODO: reward user
Log.e("Subscriber", "all tasks completed!");
txtSuccess.setText("Great success!");
}
});
}
@OnClick(R.id.btnA)
protected void onButtonAClicked() {
subjectClickedA.onNext(true);
// subjectClickedA.onCompleted();
btnA.setEnabled(false);
}
@OnClick(R.id.btnB)
protected void onButtonBClicked() {
subjectClickedB.onNext(true);
// subjectClickedB.onCompleted();
btnB.setEnabled(false);
}
@OnClick(R.id.btnC)
protected void onButtonCClicked() {
subjectClickedC.onNext(true);
// subjectClickedC.onCompleted();
btnC.setEnabled(false);
}
}
嗯發出的最近期 發出的項目,我可能失去了一些東西,但怎麼做的Observable/Subject標記爲完整?我使用的是PublishSubject.onNext(true)和onComplete(),但它似乎沒有通過zip() – twig