Cocoa Beans 0.0.54-beta0 Help

πŸ”¬ Compound Observable

Available Since 0.0.39

A compound observable is a type of observable which encapsulates multiple observables into it. It allows accessing values of multiple observables as if they are just one.

If:

  • All the observables are of the same element type

  • The observables are not changing on their own Consider using ()[collection-observable.md] instead.

Usage - The fast approach

@Test void compound() { MutableObservable<Integer> age = Observable.mutable(17); MutableObservable<String> username = Observable.mutable("thebotgame"); var compound = Observable.compound(age, username); assertEquals(17, compound.get().arg0()); assertEquals("thebotgame", compound.get().arg1()); Observable<Boolean> validUser = compound.map(args -> { String name = args.arg1(); int ageValue = args.arg0(); return ageValue >= 18 && name.length() >= 3 && name.length() <= 20; }); assertFalse(validUser.get()); // because age is 17 age.set(19); assertTrue(validUser.get()); // because age is 19 and username is "thebotgame" username.set("bo"); assertFalse(validUser.get()); // because username is "bo" and its length is less than 3 }

Usage - Prettier compounds

The default implementations of compound observables support compounding 1 up to 10 observables. You can support more arguments in the following way:

@Test void customCompound() { MutableObservable<Integer> age = Observable.mutable(24); MutableObservable<String> username = Observable.mutable("Voigon"); // The user class allows you to specify as many arguments as you would like // It also helps keeping track of your data by naming all the fields record User(int age, String username) {} Observable<User> compound = Observable.compound( // the first argument takes the list of values and constructs the User object list -> new User((int) list.get(0), (String) list.get(1)), // the second argument is the list of dependent observables we will derive our compound from List.of(age, username) ); User user = compound.get(); // now we can access the compound values in a prettier way assertEquals(24, user.age()); assertEquals("Voigon", user.username()); }

Use Cases

  • Aggregating values from several observables into one.

  • Building derived state from multiple sources.

Last modified: 07 July 2025