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