Junior — Middle
What is the purpose of the Single operator in RxJava and in which scenarios is it used?
sobes.tech AI
Answer from AI
The Single operator in RxJava represents a stream that emits exactly one item or an error. Unlike a regular Observable, which can emit multiple items, Single guarantees a single result or an error.
Purpose:
- Used for asynchronous operations that return a single value, such as a network request, database read, or computation.
Use cases:
- Fetching data from a server (e.g., loading a user profile).
- Performing operations where one result is expected (e.g., saving data with confirmation).
Example of using Single:
Single<String> single = Single.create(emitter -> {
// Asynchronous operation
String result = fetchDataFromNetwork();
if (result != null) {
emitter.onSuccess(result);
} else {
emitter.onError(new Exception("Loading error"));
}
});
single.subscribe(
data -> System.out.println("Received: " + data),
error -> System.err.println("Error: " + error.getMessage())
);