Rxjava 简明教程
RxJava - Single Observable
Single 类表示单值响应。Single observable 只能发出单个成功值或一个错误。它不发出 onComplete 事件。
The Single class represents the single value response. Single observable can only emit either a single successful value or an error. It does not emit onComplete event.
Class Declaration
以下为 io.reactivex.Single<T> 类的声明:
Following is the declaration for io.reactivex.Single<T> class −
public abstract class Single<T>
extends Object
implements SingleSource<T>
Protocol
以下为 Single Observable 采用的顺序协议:
Following is the sequential protocol that Single Observable operates −
onSubscribe (onSuccess | onError)?
Single Example
在任意编辑器中使用任何您选择的语言(如 C:\>RxJava) 创建以下 Java 程序。
Create the following Java program using any editor of your choice in, say, C:\> RxJava.
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();
}
}