androidkotlinviewmodelandroid-viewmodel

Storing current data


All the data comes from the server in bulk. I cannot influence its volume. Therefore, to reduce the number of requests, I store this data in a single ViewModel, which I share on all screens. I understand that this is not very effective. But I have no other ideas yet. Looking ahead, I want to warn you that there is no point in storing this data in the DataStore or in Room due to the possibility of changing it from another device. For this reason, when switching between screens, I create a duplicate of the data and filter the data for displaying it on the screen.

rooms.filter { it.id == roomId }

Maybe use Room as a cache? And just update the data in it every time you launch it? Forgot to add - the target OS is WearOS.


Solution

  • There is no need of using DataStore or Room. You can use Repository pattern.

    In this you just have to store your data in a Repository and then you can use it all across the app, but it won't persist the data when you kill the app you have to fetch the data every time app starts.

    Here is the image explaining repository pattern.

    enter image description here

    And here is a short example of implementation of it, you can use this as per your requirenments.

    Repository:

    class UserRepository {
        private val users = mutableListOf<User>()
    
        fun addUser(user: User) {
            users.add(user)
        }
    
        fun addAllUsers(userList: List<User>) {
            users.clear() // Clear existing data if needed
            users.addAll(userList)
        }
    
        fun getAllUsers(): List<User> = users
    }
    

    ViewModel:

    class UserViewModel(private val repository: UserRepository) : ViewModel() {
        private val _users = MutableLiveData<List<User>>()
        val users: LiveData<List<User>> get() = _users
    
        fun loadUsers() {
            _users.value = repository.getAllUsers()
        }
    
        fun addUser(user: User) {
            repository.addUser(user)
            loadUsers()  // Refresh the user list
        }
    
        fun storeFetchedUsers(fetchedUsers: List<User>) {
            repository.addAllUsers(fetchedUsers)
            loadUsers()  // Refresh the user list
        }
    }
    

    Usage in Activity/Fragment:

    class MainActivity : AppCompatActivity() {
        private val userRepository = UserRepository()
        private val viewModel: UserViewModel by viewModels { ViewModelFactory(userRepository) }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            // Simulate fetching data from an API
            val fetchedUsers = listOf(User(1, "John Doe"), User(2, "Jane Smith"))
            viewModel.storeFetchedUsers(fetchedUsers)  // Store the fetched users
    
            viewModel.users.observe(this) { users -> 
                // Update UI with user data
            }
        }
    }