Maven
<dependency>
<groupId>io.github.muthuishere</groupId>
<artifactId>declarativex</artifactId>
</dependency>
Gradle
implementation "io.github.muthuishere:declarativex"
Usage
import declarativex.Try;
import declarativex.Filter;
Instead of Writing This
List<String> results = null;
try {
results =newsService.downloadFromNyTimes(topic);
}catch (Exception e){
try {
results =newsService.downloadFromHerald(topic);
}catch (Exception e1){
try {
results =newsService.downloadFromSun(topic);
}catch (Exception e2){
}
}
}
Write This
import declarativex.Try;
results= Try.from(()->newsService.downloadFromNyTimes(topic))
.or(()->newsService.downloadFromHerald(topic))
.or(()->newsService.downloadFromSun(topic))
.get();
Or Even Better way
results= Try.any(newsService::downloadFromNyTimes,
newsService::downloadFromHerald,
newsService::downloadFromSun)
.with(topic)
.orElseGet(Arrays.asList("Some default"));
There are Additional Logging , Peek ,PeekError ,default value can convert to Optional as well
Also there is a lazy version of the same
results = Try.lazy.from(this::downloadCacheData)
.get();
//Evaluation happens only after get is Invoked