Skip to content

cyclops closures : Lazy Immutable a wrapping class for setOnce values

johnmcclean-aol edited this page Nov 21, 2016 · 4 revisions

Cyclops has merged with simple-react. Please update your bookmarks (stars :) ) to https://github.com/aol/cyclops-react

screen shot 2016-02-22 at 8 44 42 pm # LazyMutable

LazyMutable provides a thread-safe wrapper over a variable that can be set once, it implements Convertable which allows the value to be converted into various forms (such as a thread-safe AtomicReference, Optional, Stream, CompletableFuture etc).

Only the first attempt at setting a value is accepted, subsequent attempts are ignored.

Examples

//set once - sets a value directly, but only the first time it is called
//ex.a
LazyImmutable<Integer> value = new LazyImmutable<>();
Supplier s= () -> value.setOnce(10).get();

assertThat(s.get(),is(10));
assertThat(value.get(),is(10));

//ex.b
// computeIfAbsent lazily compute a value if the lazyimmutable is unset
LazyImmutable<Integer> value = new LazyImmutable<>();
Supplier s= () -> value.computeIfAbsent(()->10);
assertThat(s.get(),is(10));
assertThat(value.computeIfAbsent(()->20),is(10));

//set twice
LazyImmutable<Integer> value = new LazyImmutable<>();
Supplier s= () -> value.setOnce(10);
value.setOnce(20); //first time set
		
s.get();
		
		
assertThat(value.get(),is(20));

//flatMap
LazyImmutable<Integer> value = new LazyImmutable<Integer>();
value.setOnce(10);
LazyImmutable<Integer> value2 = value.flatMap(i->LazyImmutable.of(i+10));
assertThat(value2.get(),equalTo(20));
Clone this wiki locally