0
# Single API
1
2
Single is RxJava's reactive type for operations that emit exactly one item or an error. It's ideal for single-value async operations like network requests, database queries, or computations that produce one result.
3
4
## Capabilities
5
6
### Single Creation
7
8
Factory methods for creating Single instances.
9
10
```java { .api }
11
/**
12
* Creates a Single that emits a single item
13
* @param item the item to emit
14
* @return Single that emits the single item
15
*/
16
public static <T> Single<T> just(T item);
17
18
/**
19
* Creates a Single from a callable, executed lazily
20
* @param callable the Callable to execute
21
* @return Single that emits the callable result
22
*/
23
public static <T> Single<T> fromCallable(Callable<? extends T> callable);
24
25
/**
26
* Creates a Single using a custom emitter function
27
* @param source the SingleOnSubscribe function
28
* @return Single created from the custom emitter
29
*/
30
public static <T> Single<T> create(SingleOnSubscribe<T> source);
31
32
/**
33
* Creates a Single that emits after a delay
34
* @param delay the delay duration
35
* @param unit the time unit
36
* @return Single that emits 0L after the delay
37
*/
38
public static Single<Long> timer(long delay, TimeUnit unit);
39
40
/**
41
* Creates a Single that only calls onError
42
* @param error the error to emit
43
* @return Single that emits the error
44
*/
45
public static <T> Single<T> error(Throwable error);
46
47
/**
48
* Creates a Single that defers creation until subscription
49
* @param singleSupplier supplier of Single to defer
50
* @return Single that defers to supplied Single
51
*/
52
public static <T> Single<T> defer(Supplier<? extends SingleSource<? extends T>> singleSupplier);
53
54
/**
55
* Creates a Single from a Future
56
* @param future the Future to convert
57
* @return Single that emits the Future result
58
*/
59
public static <T> Single<T> fromFuture(Future<? extends T> future);
60
61
/**
62
* Creates a Single from an Observable source (takes first item)
63
* @param source the ObservableSource to convert
64
* @return Single with the first emitted item
65
*/
66
public static <T> Single<T> fromObservable(ObservableSource<T> source);
67
```
68
69
### Transformation Operators
70
71
Transform the emitted item or chain with other Singles.
72
73
```java { .api }
74
/**
75
* Transform the item using a mapping function
76
* @param mapper function to transform the item
77
* @return Single with transformed item
78
*/
79
public final <R> Single<R> map(Function<? super T, ? extends R> mapper);
80
81
/**
82
* Transform the item to another Single and flatten the result
83
* @param mapper function returning Single for the item
84
* @return Single from the flattened result
85
*/
86
public final <R> Single<R> flatMap(Function<? super T, ? extends SingleSource<? extends R>> mapper);
87
88
/**
89
* Transform the item to an Observable
90
* @param mapper function returning ObservableSource for the item
91
* @return Observable from the mapped result
92
*/
93
public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends ObservableSource<? extends R>> mapper);
94
95
/**
96
* Transform the item to a Flowable
97
* @param mapper function returning Publisher for the item
98
* @return Flowable from the mapped result
99
*/
100
public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publisher<? extends R>> mapper);
101
102
/**
103
* Transform the item to a Maybe
104
* @param mapper function returning MaybeSource for the item
105
* @return Maybe from the mapped result
106
*/
107
public final <R> Maybe<R> flatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper);
108
109
/**
110
* Transform the item to a Completable
111
* @param mapper function returning CompletableSource for the item
112
* @return Completable from the mapped result
113
*/
114
public final Completable flatMapCompletable(Function<? super T, ? extends CompletableSource> mapper);
115
116
/**
117
* Cast the emitted item to a different type
118
* @param clazz the target class to cast to
119
* @return Single with cast item
120
*/
121
public final <U> Single<U> cast(Class<U> clazz);
122
```
123
124
### Combination Operators
125
126
Combine multiple Single sources.
127
128
```java { .api }
129
/**
130
* Zip two Singles together
131
* @param other the other Single to zip with
132
* @param zipper function to combine the two items
133
* @return Single emitting the zipped result
134
*/
135
public final <U, R> Single<R> zipWith(SingleSource<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper);
136
137
/**
138
* Merge multiple Singles (emit items as they arrive)
139
* @param sources array of Single sources
140
* @return Observable merging all Single emissions
141
*/
142
public static <T> Observable<T> merge(SingleSource<? extends T>... sources);
143
144
/**
145
* Concatenate multiple Singles in sequence
146
* @param sources array of Single sources
147
* @return Observable concatenating all Singles
148
*/
149
public static <T> Observable<T> concat(SingleSource<? extends T>... sources);
150
151
/**
152
* Concatenate this Single with another
153
* @param other Single to concatenate after this one
154
* @return Observable concatenating both Singles
155
*/
156
public final Observable<T> concatWith(SingleSource<? extends T> other);
157
158
/**
159
* Merge this Single with another (race condition)
160
* @param other Single to merge with this one
161
* @return Single emitting the first result
162
*/
163
public final Single<T> ambWith(SingleSource<? extends T> other);
164
```
165
166
### Subscription and Scheduling
167
168
Control subscription behavior and execution context.
169
170
```java { .api }
171
/**
172
* Subscribe with a simple onSuccess callback
173
* @param onSuccess function called when item is emitted
174
* @return Disposable for managing the subscription
175
*/
176
public final Disposable subscribe(Consumer<? super T> onSuccess);
177
178
/**
179
* Subscribe with onSuccess and onError callbacks
180
* @param onSuccess function called when item is emitted
181
* @param onError function called on error
182
* @return Disposable for managing the subscription
183
*/
184
public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError);
185
186
/**
187
* Subscribe with full SingleObserver interface
188
* @param observer the SingleObserver to receive emissions
189
*/
190
public final void subscribe(SingleObserver<? super T> observer);
191
192
/**
193
* Subscribe and block until completion, returning the item
194
* @return the emitted item
195
*/
196
public final T blockingGet();
197
198
/**
199
* Specify the Scheduler for subscription operations
200
* @param scheduler the Scheduler to use for subscriptions
201
* @return Single operating on the specified scheduler
202
*/
203
public final Single<T> subscribeOn(Scheduler scheduler);
204
205
/**
206
* Specify the Scheduler for observation operations
207
* @param scheduler the Scheduler to use for observations
208
* @return Single observing on the specified scheduler
209
*/
210
public final Single<T> observeOn(Scheduler scheduler);
211
212
/**
213
* Add a delay before emitting the item
214
* @param delay the delay duration
215
* @param unit the time unit
216
* @return Single that emits after the delay
217
*/
218
public final Single<T> delay(long delay, TimeUnit unit);
219
```
220
221
### Error Handling
222
223
Handle errors in the Single stream.
224
225
```java { .api }
226
/**
227
* Return a default item when an error occurs
228
* @param defaultItem the item to emit on error
229
* @return Single that emits defaultItem on error
230
*/
231
public final Single<T> onErrorReturn(T defaultItem);
232
233
/**
234
* Return a default item using a function when an error occurs
235
* @param resumeFunction function to generate default item from error
236
* @return Single that emits result of resumeFunction on error
237
*/
238
public final Single<T> onErrorReturn(Function<? super Throwable, ? extends T> resumeFunction);
239
240
/**
241
* Resume with another Single when an error occurs
242
* @param resumeSource Single to switch to on error
243
* @return Single that switches to resumeSource on error
244
*/
245
public final Single<T> onErrorResumeNext(SingleSource<? extends T> resumeSource);
246
247
/**
248
* Retry the subscription when an error occurs
249
* @param times maximum number of retry attempts
250
* @return Single that retries up to the specified times
251
*/
252
public final Single<T> retry(long times);
253
254
/**
255
* Perform side-effect action when an error occurs
256
* @param onError action to perform on error
257
* @return Single that performs the action on error
258
*/
259
public final Single<T> doOnError(Consumer<? super Throwable> onError);
260
```
261
262
### Side Effects
263
264
Perform side-effect actions without modifying the stream.
265
266
```java { .api }
267
/**
268
* Perform an action when the item is emitted
269
* @param onSuccess action to perform when item is emitted
270
* @return Single that performs the action on success
271
*/
272
public final Single<T> doOnSuccess(Consumer<? super T> onSuccess);
273
274
/**
275
* Perform an action when subscription occurs
276
* @param onSubscribe action to perform on subscription
277
* @return Single that performs the action on subscription
278
*/
279
public final Single<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe);
280
281
/**
282
* Perform an action when disposal occurs
283
* @param onDispose action to perform on disposal
284
* @return Single that performs the action on disposal
285
*/
286
public final Single<T> doOnDispose(Action onDispose);
287
288
/**
289
* Perform actions on lifecycle events
290
* @param onSubscribe called on subscription
291
* @param onSuccess called on successful emission
292
* @param onError called on error
293
* @param onDispose called on disposal
294
* @return Single that performs actions on lifecycle events
295
*/
296
public final Single<T> doOnEvent(Consumer<? super Disposable> onSubscribe, BiConsumer<? super T, ? super Throwable> onEvent);
297
```
298
299
### Type Conversions
300
301
Convert to other reactive types.
302
303
```java { .api }
304
/**
305
* Convert to Observable
306
* @return Observable that emits the Single item
307
*/
308
public final Observable<T> toObservable();
309
310
/**
311
* Convert to Flowable
312
* @return Flowable that emits the Single item
313
*/
314
public final Flowable<T> toFlowable();
315
316
/**
317
* Convert to Maybe
318
* @return Maybe that emits the Single item
319
*/
320
public final Maybe<T> toMaybe();
321
322
/**
323
* Convert to Completable (ignores the item)
324
* @return Completable that signals completion or error
325
*/
326
public final Completable ignoreElement();
327
```
328
329
## Types
330
331
```java { .api }
332
/**
333
* Interface for creating custom Single sources
334
*/
335
public interface SingleOnSubscribe<T> {
336
void subscribe(SingleEmitter<T> emitter) throws Throwable;
337
}
338
339
/**
340
* Emitter interface for custom Single creation
341
*/
342
public interface SingleEmitter<T> {
343
void onSuccess(T value);
344
void onError(Throwable error);
345
boolean isDisposed();
346
}
347
348
/**
349
* Observer interface for Single
350
*/
351
public interface SingleObserver<T> extends Observer<T> {
352
void onSubscribe(Disposable d);
353
void onSuccess(T t);
354
void onError(Throwable e);
355
}
356
357
/**
358
* Base interface for Single sources
359
*/
360
public interface SingleSource<T> {
361
void subscribe(SingleObserver<? super T> observer);
362
}
363
```
364
365
**Usage Examples:**
366
367
```java
368
import io.reactivex.rxjava3.core.Single;
369
import io.reactivex.rxjava3.schedulers.Schedulers;
370
import java.util.concurrent.TimeUnit;
371
372
// Basic Single creation and subscription
373
Single.just("Hello World")
374
.subscribe(System.out::println);
375
376
// Async computation
377
Single.fromCallable(() -> {
378
Thread.sleep(1000);
379
return "Computed result";
380
})
381
.subscribeOn(Schedulers.io())
382
.observeOn(Schedulers.single())
383
.subscribe(
384
result -> System.out.println("Result: " + result),
385
error -> System.err.println("Error: " + error)
386
);
387
388
// Chaining Singles
389
Single.just(5)
390
.map(x -> x * x)
391
.flatMap(x -> Single.just(x + 10))
392
.subscribe(result -> System.out.println("Final: " + result));
393
394
// Error handling
395
Single.fromCallable(() -> {
396
if (Math.random() > 0.5) {
397
throw new RuntimeException("Random error");
398
}
399
return "Success";
400
})
401
.onErrorReturn("Default value")
402
.subscribe(System.out::println);
403
404
// Combining Singles
405
Single<String> single1 = Single.just("Hello");
406
Single<String> single2 = Single.just("World");
407
408
single1.zipWith(single2, (s1, s2) -> s1 + " " + s2)
409
.subscribe(System.out::println);
410
411
// Timeout handling
412
Single.timer(2, TimeUnit.SECONDS)
413
.map(tick -> "Delayed result")
414
.timeout(1, TimeUnit.SECONDS)
415
.onErrorReturn("Timeout occurred")
416
.subscribe(System.out::println);
417
```