CompletableObserver简单的用法跟踪一个任务的结束,不处理复杂的数据传导,例如:
package zhangphil.app;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.concurrent.Callable;
import io.reactivex.Completable;
import io.reactivex.CompletableObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
test();
}
private void test() {
Completable.fromCallable(new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "任务结束!");
return null;
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getCompletableObserver());
}
private CompletableObserver getCompletableObserver() {
return new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG, "onSubscribe " + System.currentTimeMillis());
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete " + System.currentTimeMillis());
}
@Override
public void onError(Throwable e) {
}
};
}
}
代码运行输出:
05-16 14:01:20.908 12292-12292/zhangphil.app D/MainActivity: onSubscribe 1494914480908
05-16 14:01:20.945 12292-12292/zhangphil.app D/InputTransport: Input channel constructed: fd=73
05-16 14:01:20.945 12292-12292/zhangphil.app D/ViewRootImpl@99677a6[MainActivity]: setView = DecorView@de9b5e7[MainActivity] touchMode=true
05-16 14:01:20.949 12292-12292/zhangphil.app W/Activity: AppLock checkAppLockState locked:false verifying:false pkgName = zhangphil.app isInMultiWindowMode:false
05-16 14:01:20.985 12292-12292/zhangphil.app D/ViewRootImpl@99677a6[MainActivity]: MSG_RESIZED_REPORT: ci=Rect(0, 81 - 0, 0) vi=Rect(0, 81 - 0, 0) or=1
05-16 14:01:20.986 12292-12292/zhangphil.app D/ViewRootImpl@99677a6[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1
05-16 14:01:20.986 12292-12292/zhangphil.app I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus
05-16 14:01:20.988 12292-12292/zhangphil.app D/InputTransport: Input channel constructed: fd=74
05-16 14:01:25.911 12292-23777/zhangphil.app D/MainActivity: 任务结束!
05-16 14:01:25.912 12292-12292/zhangphil.app D/MainActivity: onComplete 1494914485912