Yet Another OTP generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OtpListViewModel.kt 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package com.chameth.yaotp.viewmodel
  2. import androidx.lifecycle.ViewModel
  3. import com.chameth.yaotp.accounts.Account
  4. import java.util.concurrent.CopyOnWriteArrayList
  5. class OtpListViewModel : ViewModel() {
  6. private val observers = CopyOnWriteArrayList<AccountObserver>()
  7. private val accounts = ArrayList<Account>()
  8. private val accountViewModels = ArrayList<OtpItemViewModel>()
  9. val numberOfAccounts: Int
  10. get() = accounts.size
  11. fun getViewModelForAccount(accountId: Int) = accountViewModels[accountId]
  12. fun addAccount(account: Account) {
  13. accounts.add(account)
  14. accountViewModels.add(OtpItemViewModel().also { it.account = account })
  15. observers.forEach { it.accountAdded(accounts.size - 1) }
  16. }
  17. fun removeAccount(account: Account) {
  18. val index = accounts.indexOf(account)
  19. if (index >= 0) {
  20. accounts.removeAt(index)
  21. accountViewModels.removeAt(index)
  22. observers.forEach { it.accountRemoved(index) }
  23. }
  24. }
  25. fun addObserver(observer: AccountObserver) = observers.add(observer)
  26. fun removeObserver(observer: AccountObserver) = observers.remove(observer)
  27. interface AccountObserver {
  28. fun accountAdded(position: Int)
  29. fun accountRemoved(position: Int)
  30. }
  31. }