What types of map operators do you know in RxJava?
sobes.tech AI
Answer from AI
The map operator in RxJava has several variants, differing in their functionality for transforming data.
Main types of map operators:
-
map: Transforms each element of the source sequence using a specified function.// Converts numbers to their string representations Observable<Integer> source = Observable.just(1, 2, 3); Observable<String> result = source.map(i -> String.valueOf(i)); -
flatMap: Transforms each element into a new ObservableSource, then "flattens" these into a single output sequence. The order of elements may not be preserved.// Transforms a number into an Observable of another number Observable<Integer> source = Observable.just(1, 2, 3); Observable<Integer> result = source.flatMap(i -> Observable.just(i * 10)); -
concatMap: Similar toflatMap, but guarantees that the ObservableSources are emitted sequentially, preserving order.// Sequentially transforms a number into an Observable of another number Observable<Integer> source = Observable.just(1, 2, 3); Observable<Integer> result = source.concatMap(i -> Observable.just(i * 10)); -
switchMap: Transforms each element into a new ObservableSource. When a new element arrives, it unsubscribes from the previous Observable and subscribes to the new one. It emits only from the "latest" Observable.// Switches to a new Observable on each new number, cancelling previous Observable<Integer> source = Observable.just(1, 2, 3); Observable<Integer> result = source.switchMap(i -> Observable.just(i * 10).delay(100, TimeUnit.MILLISECONDS)); // Adds delay for demonstration -
mapNotNull(in Kotlin): A special operator available with RxKotlin. It functions likemap, but automatically filters outnullvalues returned by the transformation function.// Filters out nulls in Kotlin val source = Observable.just(1, 2, null, 4) val result = source.mapNotNull { it?.toString() }
These operators provide powerful tools for data transformation depending on the desired behavior and stream management.