Cocoa Beans 0.0.54-beta0 Help

🪞 Mapping Collection Observable

Available Since 0.0.50

Introduction

mapEach is a per-element transformation operator on a CollectionObservable. It produces a derived collection whose elements come from applying a mapper to each element of the source.

This is different from Observable#map, which transforms the whole collection into a single value. mapEach keeps the collection-shape and transforms only its elements:

ListObservable<GamePlayer> players = Observable.list(); ListObservable<String> names = players.mapEach(GamePlayer::name);

If your mapper returns an Observable<R> you want to follow live, use 🪐 Flat Mapping Collection Observable instead.

Usage

@Test void mapEachSample() { ListObservable<String> names = Observable.list(); // mapEach derives a ListObservable<Integer> of per-element lengths ListObservable<Integer> lengths = names.mapEach(String::length); names.add("kfir"); names.add("apartium"); assertEquals(List.of(4, 8), lengths.get()); names.add("voigon"); assertEquals(List.of(4, 8, 6), lengths.get()); names.remove("kfir"); assertEquals(List.of(8, 6), lengths.get()); }

Behavior

  • Type-preserving:

    • ListObservable<E> → ListObservable<R>

    • SetObservable<E> → SetObservable<R>

  • The mapper runs lazily on get(), only when the source has changed since the previous call.

  • The result is cached between calls; the mapper is not re-run for unrelated reads.

  • Updates fire when the source collection changes (add / remove / clear / reorder).

    • mapEach does not subscribe to anything inside the mapped values — only the source collection.

Notes per collection type

Source

Result

Effect of duplicates

ListObservable<E>

ListObservable<R>

Order and duplicates preserved

SetObservable<E>

SetObservable<R>

Mapped collisions deduplicate (set semantics)

Advantages

  • 🪶 Cheap: lazy + cached, mapper runs once per element per source change

  • 🧱 Composable: chains naturally with filter and flatMapEach

  • 🧹 No leaks: nothing else is observed; only the source collection

  • ⛓ Type-preserving: a mapped ListObservable stays a ListObservable

Last modified: 09 May 2026