Using LiveData
Livebox supports converting the result observable to another type by using a custom adapter. There are two built-in adapters that can be used, however you don't need to call the manually, instead use the auxiliary methods .asLiveData()
and scoped()
.
// Create validators
Validator<UsersRes> ageValidator = AgeValidator.create(TimeUnit.MINUTES.toMillis(2));
Validator<UsersRes> persistentDiskValidator = (key, item) -> Objects.nonNull(item) && !item.getItems().isEmpty();
// Builds an instance of Livebox using LiveboxBuilder class.
Livebox<UsersRes, Users> usersBox = new LiveboxBuilder<UsersRes, Users>()
.withKey("get_users")
.fetch(api::getUserList, UsersRes.class)
.addSource(Sources.MEMORY_LRU, ageValidator)
.addSource(Sources.DISK_PERSISTENT, persistentDiskValidator)
.addConverter(UsersRes.class, usersRes -> Optional.of(Users.fromUsersRes(usersRes)))
.retryOnFailure()
.build();
usersBox.asLiveData().observe(this, users -> Log.d(TAG, "UsersRes: " + users));
In the above example we call .asLiveData()
that returns a LiveData instance.
Last updated