Designing a financial application with offline support using the MVVM (Model-View-ViewModel) architecture while adhering to SOLID principles involves careful planning of how data is managed, stored locally, and synchronized with cloud storage. Below is a comprehensive guide, including a CRUD operations example for an "Accounts List" view, illustrating how to implement this system effectively.
High-Level Architecture
Components
- Model: Represents the data structure (e.g.,
Account).
- View: UI components displaying data and capturing user interactions.
- ViewModel: Acts as a mediator between the View and Model, handling logic and data transformations.
- Repository: Manages data operations, deciding whether to fetch from local storage or remote source.
- Data Sources:
- Local Data Source: Handles local storage (e.g., SQLite, Room, Realm).
- Remote Data Source: Manages cloud storage interactions (e.g., Firebase, REST APIs).
Offline Support and Synchronization
- Local Storage: Ensures the app functions offline by storing data locally.
- Synchronization Mechanism: Detects network availability and syncs local changes with the cloud, resolving conflicts as necessary.
Adhering to SOLID Principles
- Single Responsibility: Each class has one responsibility (e.g.,
AccountRepository handles data operations).
- Open/Closed: Classes are open for extension but closed for modification.
- Liskov Substitution: Subtypes can replace their base types without altering the correctness.
- Interface Segregation: Interfaces are specific to client needs.
- Dependency Inversion: High-level modules depend on abstractions, not on concrete implementations.
Implementation Example
We'll use Kotlin with Android as the platform for this example, utilizing Room for local storage and a REST API for remote operations. Libraries such as Retrofit for networking and Coroutines for asynchronous operations will also be used.
1. Define the Account Model
// domain/model/Account.kt
data class Account(
val id: String,
val name: String,
val balance: Double,
val lastModified: Long // Timestamp for synchronization
)
2. Create Repository Interfaces
// domain/repository/AccountRepository.kt
interface AccountRepository {
suspend fun getAccounts(): List<Account>
suspend fun getAccountById(id: String): Account?
suspend fun addAccount(account: Account)
suspend fun updateAccount(account: Account)
suspend fun deleteAccount(id: String)
}
3. Define Data Sources
Local Data Source
// data/local/AccountDao.kt
@Dao
interface AccountDao {
@Query("SELECT * FROM accounts")
suspend fun getAllAccounts(): List<AccountEntity>
@Query("SELECT * FROM accounts WHERE id = :id")
suspend fun getAccountById(id: String): AccountEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAccount(account: AccountEntity)
@Update
suspend fun updateAccount(account: AccountEntity)
@Delete
suspend fun deleteAccount(account: AccountEntity)
}
// data/local/AccountEntity.kt
@Entity(tableName = "accounts")
data class AccountEntity(
@PrimaryKey val id: String,
val name: String,
val balance: Double,
val lastModified: Long
)
fun AccountEntity.toDomain() = Account(id, name, balance, lastModified)
fun Account.toEntity() = AccountEntity(id, name, balance, lastModified)
Remote Data Source
// data/remote/AccountApiService.kt
interface AccountApiService {
@GET("accounts")
suspend fun fetchAccounts(): List<AccountDto>
@POST("accounts")
suspend fun createAccount(@Body account: AccountDto): AccountDto
@PUT("accounts/{id}")
suspend fun updateAccount(@Path("id") id: String, @Body account: AccountDto): AccountDto
@DELETE("accounts/{id}")
suspend fun deleteAccount(@Path("id") id: String)
}
// data/remote/AccountDto.kt
data class AccountDto(
val id: String,
val name: String,
val balance: Double,
val lastModified: Long
)
fun AccountDto.toDomain() = Account(id, name, balance, lastModified)
fun Account.toDto() = AccountDto(id, name, balance, lastModified)
4. Implement the Repository
// data/repository/AccountRepositoryImpl.kt
class AccountRepositoryImpl(
private val localDataSource: AccountDao,
private val remoteDataSource: AccountApiService,
private val networkHelper: NetworkHelper
) : AccountRepository {
override suspend fun getAccounts(): List<Account> {
return if (networkHelper.isNetworkAvailable()) {
val remoteAccounts = remoteDataSource.fetchAccounts().map { it.toDomain() }
// Update local database
localDataSource.insertAccounts(remoteAccounts.map { it.toEntity() })
remoteAccounts
} else {
// Fetch from local storage
localDataSource.getAllAccounts().map { it.toDomain() }
}
}
override suspend fun getAccountById(id: String): Account? {
return if (networkHelper.isNetworkAvailable()) {
val remoteAccount = remoteDataSource.fetchAccountById(id)?.toDomain()
remoteAccount?.let {
localDataSource.insertAccount(it.toEntity())
}
remoteAccount
} else {
localDataSource.getAccountById(id)?.toDomain()
}
}
override suspend fun addAccount(account: Account) {
// Add to local storage first
localDataSource.insertAccount(account.toEntity())
if (networkHelper.isNetworkAvailable()) {
// Sync with remote
remoteDataSource.createAccount(account.toDto())
} else {
// Mark for synchronization
// Implement a mechanism to track pending operations
}
}
override suspend fun updateAccount(account: Account) {
localDataSource.updateAccount(account.toEntity())
if (networkHelper.isNetworkAvailable()) {
remoteDataSource.updateAccount(account.id, account.toDto())
} else {
// Mark for synchronization
}
}
override suspend fun deleteAccount(id: String) {
val account = localDataSource.getAccountById(id)
account?.let {
localDataSource.deleteAccount(it)
}
if (networkHelper.isNetworkAvailable()) {
remoteDataSource.deleteAccount(id)
} else {
// Mark for synchronization
}
}
}
Note: For brevity, the above implementation assumes certain helper methods and synchronization mechanisms. In a real-world scenario, you'd need to implement mechanisms to queue operations while offline and handle conflicts during synchronization.
5. Set Up ViewModel
// presentation/viewmodel/AccountViewModel.kt
class AccountViewModel(private val repository: AccountRepository) : ViewModel() {
private val _accounts = MutableLiveData<List<Account>>()
val accounts: LiveData<List<Account>> get() = _accounts
private val _error = MutableLiveData<String>()
val error: LiveData<String> get() = _error
fun loadAccounts() {
viewModelScope.launch {
try {
val accountList = repository.getAccounts()
_accounts.postValue(accountList)
} catch (e: Exception) {
_error.postValue(e.message)
}
}
}
fun addAccount(account: Account) {
viewModelScope.launch {
try {
repository.addAccount(account)
loadAccounts()
} catch (e: Exception) {
_error.postValue(e.message)
}
}
}
fun updateAccount(account: Account) {
viewModelScope.launch {
try {
repository.updateAccount(account)
loadAccounts()
} catch (e: Exception) {
_error.postValue(e.message)
}
}
}
fun deleteAccount(id: String) {
viewModelScope.launch {
try {
repository.deleteAccount(id)
loadAccounts()
} catch (e: Exception) {
_error.postValue(e.message)
}
}
}
}
6. Design the View (e.g., Activity or Fragment)
// presentation/view/AccountListFragment.kt
class AccountListFragment : Fragment(R.layout.fragment_account_list) {
private val viewModel: AccountViewModel by viewModels {
// Assume a ViewModelFactory is implemented to provide AccountRepository
}
private lateinit var adapter: AccountAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter = AccountAdapter { account ->
// Handle account item click
}
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
viewModel.accounts.observe(viewLifecycleOwner) { accounts ->
adapter.submitList(accounts)
}
viewModel.error.observe(viewLifecycleOwner) { error ->
Toast.makeText(context, error, Toast.LENGTH_SHORT).show()
}
swipeRefreshLayout.setOnRefreshListener {
viewModel.loadAccounts()
swipeRefreshLayout.isRefreshing = false
}
fabAddAccount.setOnClickListener {
// Navigate to Add Account Screen
}
viewModel.loadAccounts()
}
}
7. Adapter for RecyclerView
// presentation/view/AccountAdapter.kt
class AccountAdapter(private val onItemClick: (Account) -> Unit) :
ListAdapter<Account, AccountAdapter.AccountViewHolder>(AccountDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AccountViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_account, parent, false)
return AccountViewHolder(view)
}
override fun onBindViewHolder(holder: AccountViewHolder, position: Int) {
holder.bind(getItem(position))
}
inner class AccountViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val nameText: TextView = itemView.findViewById(R.id.tvAccountName)
private val balanceText: TextView = itemView.findViewById(R.id.tvAccountBalance)
fun bind(account: Account) {
nameText.text = account.name
balanceText.text = "$${account.balance}"
itemView.setOnClickListener { onItemClick(account) }
}
}
}
class AccountDiffCallback : DiffUtil.ItemCallback<Account>() {
override fun areItemsTheSame(oldItem: Account, newItem: Account): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Account, newItem: Account): Boolean =
oldItem == newItem
}
8. Network Helper
// util/NetworkHelper.kt
class NetworkHelper(private val context: Context) {
fun isNetworkAvailable(): Boolean {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connectivityManager.activeNetworkInfo?.isConnected == true
}
}
9. Dependency Injection (e.g., using Hilt)
// di/AppModule.kt
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
fun provideAccountDao(db: AppDatabase): AccountDao = db.accountDao()
@Provides
fun provideAccountApiService(): AccountApiService {
return Retrofit.Builder()
.baseUrl("https://api.yourfinanceapp.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(AccountApiService::class.java)
}
@Provides
fun provideNetworkHelper(@ApplicationContext context: Context) = NetworkHelper(context)
@Provides
fun provideAccountRepository(
localDataSource: AccountDao,
remoteDataSource: AccountApiService,
networkHelper: NetworkHelper
): AccountRepository = AccountRepositoryImpl(localDataSource, remoteDataSource, networkHelper)
}
Synchronization Strategy
To handle synchronization between local and remote data, especially when the app goes from offline to online, consider the following strategies:
- Timestamp-Based Sync: Use
lastModified timestamps to determine the most recent changes.
- Operation Queue: Maintain a queue of operations performed offline and replay them when back online.
- Conflict Resolution: Define rules to handle conflicts, such as last-write-wins or prompting the user.
Implementing synchronization would involve:
- Observing network status changes.
- Triggering synchronization processes when the network becomes available.
- Handling retries and failures gracefully.
Conclusion
This example demonstrates how to design a financial app with offline support using the MVVM architecture while adhering to SOLID principles. The key is to abstract data sources using the Repository pattern, ensure single responsibility for each class, and depend on abstractions rather than concrete implementations. Proper synchronization mechanisms are essential for maintaining data integrity between local storage and cloud services.
Implementing such a system requires careful consideration of edge cases and robust error handling, especially around network reliability and data consistency. Leveraging architectural patterns and principles will ensure your app remains maintainable, scalable, and resilient.