I'm having a problem with RxJava3 and Room, I have the entities and domain models as below:
AccountEntity.java
@Entity
public class AccountEntity {
private UUID id;
private String name;
}
Account.java
public class Account {
private UUID id;
private String name;
private double balance;
private double totalIncome;
private double totalExpense;
public void computeAmount(List<Transaction> transactions) {
// Compute balance, income and expense from a list of transactions
}
}
TransactionEntity.java
@Entity
public class TransactionEntity {
private UUID id;
private UUID accountId;
private TransactionType type;
private double amount;
}
Transaction.java
public class Transaction {
private UUID id;
private UUID accountId;
private TransactionType type;
private double amount;
}
And the DAO methods:
@Query("SELECT * FROM my_account ORDER BY last_modified_time DESC")
Flowable<List<AccountEntity>> getAllAccounts();
@Query("SELECT * FROM my_transaction WHERE account_id = :accountId")
Flowable<List<TransactionEntity>> getTransactionsByAccountId(UUID accountId);
I have a screen (Fragment) where a list of accounts is displayed with their balance, income and expense. In the ViewModel of that fragment, I set up the LiveData as below (the repositories only call DAO methods and map the entities to domain models, and they return flowable of domain models):
Flowable<List<Account>> flow1;
flow1 = accountRepository.getAllAccounts().flatMap(accounts -> {
return Flowable.fromIterable(accounts).flatMap(account -> {
return transactionRepository.getTransactionsByAccountId(account.getId()).map(transactions -> {
account.computeAmount(transactions);
return account;
});
})
.toList()
.toFlowable();
})
.doOnNext(accounts -> {
// Do something with the emitted list of accounts
});
LiveData<List<Account>> accountList = LiveDataReactiveStreams.fromPublisher(flow1);
The problem here is, I can observe new data from both flowable sources but I have no way to get the finally emitted list of accounts because of toList(), which only emits when completed. However I have yet to come up with an idea to accomplish what I need, which is to get the list of accounts with balance, income and expense (calculated from a list of Transaction associated with each Account) and to get new data every time a change is made in either entity table (hence Flowable in both DAO methods).
How should I fix this issue? I'm quite new to RxJava so I'm not exactly familiar to all the concepts and operators. Thank you in advance.