Rxjava 简明教程
RxJava - Single Observable
Single 类表示单值响应。Single observable 只能发出单个成功值或一个错误。它不发出 onComplete 事件。
Class Declaration
以下为 io.reactivex.Single<T> 类的声明:
public abstract class Single<T>
extends Object
implements SingleSource<T>
Single Example
在任意编辑器中使用任何您选择的语言(如 C:\>RxJava) 创建以下 Java 程序。
ObservableTester.java
import java.util.concurrent.TimeUnit;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
public class ObservableTester {
public static void main(String[] args) throws InterruptedException {
//Create the observable
Single<String> testSingle = Single.just("Hello World");
//Create an observer
Disposable disposable = testSingle
.delay(2, TimeUnit.SECONDS, Schedulers.io())
.subscribeWith(
new DisposableSingleObserver<String>() {
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onSuccess(String value) {
System.out.println(value);
}
});
Thread.sleep(3000);
//start observing
disposable.dispose();
}
}