or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

completable.mddisposables.mderror-handling.mdflowable.mdindex.mdmaybe.mdobservable.mdschedulers.mdsingle.mdsubjects.md

single.mddocs/

0

# Single Values

1

2

Reactive type that emits exactly one value or an error. Single is perfect for async operations that return a single result like HTTP requests, database queries, or any operation that produces one outcome.

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 the provided item then completes

13

*/

14

public static <T> Single<T> just(T item);

15

16

/**

17

* Creates a Single from a Callable that will be called for each observer

18

*/

19

public static <T> Single<T> fromCallable(Callable<? extends T> callable);

20

21

/**

22

* Creates a Single from a Future

23

*/

24

public static <T> Single<T> fromFuture(Future<? extends T> future);

25

26

/**

27

* Creates a Single using the provided SingleOnSubscribe function

28

*/

29

public static <T> Single<T> create(SingleOnSubscribe<T> source);

30

31

/**

32

* Creates a Single that emits after a delay

33

*/

34

public static Single<Long> timer(long delay, TimeUnit unit);

35

public static Single<Long> timer(long delay, TimeUnit unit, Scheduler scheduler);

36

37

/**

38

* Creates a Single that only calls onError

39

*/

40

public static <T> Single<T> error(Throwable exception);

41

public static <T> Single<T> error(Callable<? extends Throwable> errorSupplier);

42

43

/**

44

* Creates a Single that never emits

45

*/

46

public static <T> Single<T> never();

47

48

/**

49

* Defers Single creation until subscription

50

*/

51

public static <T> Single<T> defer(Callable<? extends SingleSource<? extends T>> singleSupplier);

52

53

/**

54

* Creates a Single from an ObservableSource that emits exactly one item

55

*/

56

public static <T> Single<T> fromObservable(ObservableSource<T> observableSource);

57

```

58

59

### Transformation Operators

60

61

Transform the value emitted by a Single.

62

63

```java { .api }

64

/**

65

* Transforms the item using a function

66

*/

67

public final <R> Single<R> map(Function<? super T, ? extends R> mapper);

68

69

/**

70

* Transforms the item into another Single and flattens the result

71

*/

72

public final <R> Single<R> flatMap(Function<? super T, ? extends SingleSource<? extends R>> mapper);

73

74

/**

75

* Transforms the item into an Observable

76

*/

77

public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends ObservableSource<? extends R>> mapper);

78

79

/**

80

* Transforms the item into a Flowable

81

*/

82

public final <R> Flowable<R> flatMapFlowable(Function<? super T, ? extends Publisher<? extends R>> mapper);

83

84

/**

85

* Transforms the item into a Maybe

86

*/

87

public final <R> Maybe<R> flatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper);

88

89

/**

90

* Transforms the item into a Completable

91

*/

92

public final Completable flatMapCompletable(Function<? super T, ? extends CompletableSource> mapper);

93

94

/**

95

* Casts the item to the specified type

96

*/

97

public final <U> Single<U> cast(Class<U> clazz);

98

```

99

100

### Filtering and Conditional Operators

101

102

Apply conditions to Single operations.

103

104

```java { .api }

105

/**

106

* Converts Single to Maybe, filtering based on predicate

107

*/

108

public final Maybe<T> filter(Predicate<? super T> predicate);

109

110

/**

111

* Tests whether the Single emits an item that satisfies a condition

112

*/

113

public final Single<Boolean> contains(Object item);

114

```

115

116

### Error Handling

117

118

Handle errors in Single operations.

119

120

```java { .api }

121

/**

122

* Returns a Single that emits a specified item if the source emits an error

123

*/

124

public final Single<T> onErrorReturn(Function<? super Throwable, ? extends T> valueSupplier);

125

public final Single<T> onErrorReturn(T value);

126

127

/**

128

* Returns a Single that switches to another Single if the source emits an error

129

*/

130

public final Single<T> onErrorResumeNext(Function<? super Throwable, ? extends SingleSource<? extends T>> resumeFunction);

131

public final Single<T> onErrorResumeNext(SingleSource<? extends T> resumeSingleSource);

132

133

/**

134

* Retry on error

135

*/

136

public final Single<T> retry();

137

public final Single<T> retry(long times);

138

public final Single<T> retry(BiPredicate<? super Integer, ? super Throwable> predicate);

139

public final Single<T> retryWhen(Function<? super Flowable<Throwable>, ? extends Publisher<?>> handler);

140

```

141

142

### Combining Singles

143

144

Combine multiple Singles.

145

146

```java { .api }

147

/**

148

* Combines two Singles using a combiner function

149

*/

150

public static <T1, T2, R> Single<R> zip(

151

SingleSource<? extends T1> source1,

152

SingleSource<? extends T2> source2,

153

BiFunction<? super T1, ? super T2, ? extends R> zipper

154

);

155

156

/**

157

* Zips up to 9 Singles

158

*/

159

public static <T1, T2, T3, R> Single<R> zip(

160

SingleSource<? extends T1> source1,

161

SingleSource<? extends T2> source2,

162

SingleSource<? extends T3> source3,

163

Function3<? super T1, ? super T2, ? super T3, ? extends R> zipper

164

);

165

166

/**

167

* Returns the first Single to emit successfully

168

*/

169

public static <T> Single<T> amb(SingleSource<? extends T>... sources);

170

public static <T> Single<T> amb(Iterable<? extends SingleSource<? extends T>> sources);

171

172

/**

173

* Concatenates Singles sequentially

174

*/

175

public static <T> Observable<T> concat(SingleSource<? extends T>... sources);

176

public static <T> Observable<T> concat(Iterable<? extends SingleSource<? extends T>> sources);

177

178

/**

179

* Merges Singles into an Observable

180

*/

181

public static <T> Observable<T> merge(SingleSource<? extends T>... sources);

182

public static <T> Observable<T> merge(Iterable<? extends SingleSource<? extends T>> sources);

183

```

184

185

### Threading

186

187

Control execution context for Singles.

188

189

```java { .api }

190

/**

191

* Specifies the Scheduler on which the Single will operate

192

*/

193

public final Single<T> subscribeOn(Scheduler scheduler);

194

195

/**

196

* Specifies the Scheduler on which observers will be notified

197

*/

198

public final Single<T> observeOn(Scheduler scheduler);

199

```

200

201

### Timing Operations

202

203

Add delays and timeouts to Singles.

204

205

```java { .api }

206

/**

207

* Delays the emission of the success signal

208

*/

209

public final Single<T> delay(long time, TimeUnit unit);

210

public final Single<T> delay(long time, TimeUnit unit, Scheduler scheduler);

211

212

/**

213

* Adds a timeout to the Single

214

*/

215

public final Single<T> timeout(long timeout, TimeUnit timeUnit);

216

public final Single<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler);

217

public final Single<T> timeout(long timeout, TimeUnit timeUnit, SingleSource<? extends T> other);

218

```

219

220

### Conversion Operations

221

222

Convert Single to other reactive types.

223

224

```java { .api }

225

/**

226

* Converts Single to Observable

227

*/

228

public final Observable<T> toObservable();

229

230

/**

231

* Converts Single to Flowable

232

*/

233

public final Flowable<T> toFlowable();

234

235

/**

236

* Converts Single to Maybe

237

*/

238

public final Maybe<T> toMaybe();

239

240

/**

241

* Converts Single to Completable (ignoring the value)

242

*/

243

public final Completable toCompletable();

244

```

245

246

### Subscription and Consumption

247

248

Subscribe to a Single and consume the emitted value.

249

250

```java { .api }

251

/**

252

* Subscribes with separate callbacks

253

*/

254

public final Disposable subscribe();

255

public final Disposable subscribe(Consumer<? super T> onSuccess);

256

public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError);

257

258

/**

259

* Subscribes with a SingleObserver

260

*/

261

public final void subscribe(SingleObserver<? super T> observer);

262

263

/**

264

* Blocking operations - use with caution

265

*/

266

public final T blockingGet();

267

```

268

269

### Utility Operations

270

271

Additional utility operations for Singles.

272

273

```java { .api }

274

/**

275

* Caches the result of the Single

276

*/

277

public final Single<T> cache();

278

279

/**

280

* Performs side-effects without affecting the Single

281

*/

282

public final Single<T> doOnSuccess(Consumer<? super T> onSuccess);

283

public final Single<T> doOnError(Consumer<? super Throwable> onError);

284

public final Single<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe);

285

public final Single<T> doOnDispose(Action onDispose);

286

public final Single<T> doFinally(Action onFinally);

287

288

/**

289

* Repeats the Single subscription

290

*/

291

public final Observable<T> repeat();

292

public final Observable<T> repeat(long times);

293

```

294

295

## Usage Examples

296

297

**Basic Single Creation and Subscription:**

298

299

```java

300

import io.reactivex.Single;

301

import io.reactivex.SingleObserver;

302

import io.reactivex.disposables.Disposable;

303

304

// Simple Single

305

Single<String> source = Single.just("Hello Single");

306

307

source.subscribe(new SingleObserver<String>() {

308

@Override

309

public void onSubscribe(Disposable d) {

310

System.out.println("Subscribed");

311

}

312

313

@Override

314

public void onSuccess(String value) {

315

System.out.println("Success: " + value);

316

}

317

318

@Override

319

public void onError(Throwable e) {

320

System.err.println("Error: " + e.getMessage());

321

}

322

});

323

324

// Lambda-style subscription

325

source.subscribe(

326

value -> System.out.println("Got: " + value),

327

error -> error.printStackTrace()

328

);

329

```

330

331

**Async Operations with Single:**

332

333

```java

334

import java.util.concurrent.Callable;

335

336

// HTTP request simulation

337

Single<String> httpRequest = Single.fromCallable(() -> {

338

// Simulate network call

339

Thread.sleep(1000);

340

return "Response from server";

341

}).subscribeOn(Schedulers.io())

342

.observeOn(AndroidSchedulers.mainThread()); // or Schedulers.computation()

343

344

httpRequest.subscribe(

345

response -> System.out.println("HTTP Response: " + response),

346

error -> System.err.println("HTTP Error: " + error)

347

);

348

```

349

350

**Error Handling with Single:**

351

352

```java

353

Single<Integer> riskyOperation = Single.fromCallable(() -> {

354

if (Math.random() > 0.5) {

355

throw new RuntimeException("Random failure");

356

}

357

return 42;

358

});

359

360

// Handle errors with fallback value

361

riskyOperation

362

.onErrorReturn(throwable -> {

363

System.out.println("Error occurred: " + throwable.getMessage());

364

return -1; // Fallback value

365

})

366

.subscribe(result -> System.out.println("Result: " + result));

367

368

// Retry on failure

369

riskyOperation

370

.retry(3) // Retry up to 3 times

371

.subscribe(

372

result -> System.out.println("Success: " + result),

373

error -> System.out.println("Failed after retries: " + error)

374

);

375

```

376

377

**Combining Singles:**

378

379

```java

380

Single<String> firstName = Single.just("John");

381

Single<String> lastName = Single.just("Doe");

382

383

// Zip two Singles together

384

Single<String> fullName = Single.zip(firstName, lastName,

385

(first, last) -> first + " " + last);

386

387

fullName.subscribe(name -> System.out.println("Full name: " + name));

388

389

// Chain Singles

390

Single<String> greeting = firstName

391

.flatMap(name -> Single.just("Hello, " + name + "!"));

392

393

greeting.subscribe(msg -> System.out.println(msg));

394

```

395

396

**Transforming Single to Other Types:**

397

398

```java

399

Single<Integer> source = Single.just(5);

400

401

// Convert to Observable

402

Observable<Integer> observable = source.toObservable();

403

observable.subscribe(System.out::println);

404

405

// Convert to Maybe

406

Maybe<Integer> maybe = source.toMaybe();

407

maybe.subscribe(System.out::println);

408

409

// Convert to Completable (ignoring value)

410

Completable completable = source.toCompletable();

411

completable.subscribe(() -> System.out.println("Completed"));

412

```

413

414

**Custom Single Creation:**

415

416

```java

417

Single<String> customSingle = Single.create(emitter -> {

418

try {

419

// Simulate some work

420

String result = performSomeOperation();

421

emitter.onSuccess(result);

422

} catch (Exception e) {

423

emitter.onError(e);

424

}

425

});

426

427

private String performSomeOperation() {

428

// Simulate work

429

return "Operation completed";

430

}

431

```

432

433

## Types

434

435

```java { .api }

436

/**

437

* Observer interface for Singles

438

*/

439

public interface SingleObserver<T> {

440

void onSubscribe(Disposable d);

441

void onSuccess(T t);

442

void onError(Throwable e);

443

}

444

445

/**

446

* Functional interface for creating Singles

447

*/

448

public interface SingleOnSubscribe<T> {

449

void subscribe(SingleEmitter<T> emitter) throws Exception;

450

}

451

452

/**

453

* Emitter for SingleOnSubscribe

454

*/

455

public interface SingleEmitter<T> {

456

void onSuccess(T t);

457

void onError(Throwable t);

458

void setDisposable(Disposable d);

459

void setCancellable(Cancellable c);

460

boolean isDisposed();

461

}

462

463

/**

464

* Base interface for Single sources

465

*/

466

public interface SingleSource<T> {

467

void subscribe(SingleObserver<? super T> observer);

468

}

469

```