- 
                Notifications
    
You must be signed in to change notification settings  - Fork 3.9k
 
Description
Is there an existing issue for this?
- I have searched the existing issues
 
Describe the problem
In BookmarksViewModel, the shouldDisplayUndoBookmark variable is declared in a way that allows it to be directly modified from outside the ViewModel.
As a result, the state can be unintentionally changed by external components, and the internal state management details are exposed, violating the principle of encapsulation.
@HiltViewModel
class BookmarksViewModel @Inject constructor(
    private val userDataRepository: UserDataRepository,
    userNewsResourceRepository: UserNewsResourceRepository,
) : ViewModel() {
    var shouldDisplayUndoBookmark by mutableStateOf(false)
    ....
}Describe the solution
You can choose either of the following approaches:
1. Add private set to the variable
Change the declaration of shouldDisplayUndoBookmark to use a private set, so that the value can only be modified within the BookmarksViewModel itself. This prevents external classes or Composables from updating the state directly.
// AS-IS
var shouldDisplayUndoBookmark by mutableStateOf(false)
// TO-BE
var shouldDisplayUndoBookmark by mutableStateOf(false)
    private set2. Use a backing property for encapsulation
Use a MutableStateFlow for internal state management and expose it as an immutable StateFlow for external observation. This ensures that the state can only be modified within the ViewModel, while still allowing external components to observe its value.
// AS-IS
var shouldDisplayUndoBookmark by mutableStateOf(false)
// TO-BE
private val _shouldDisplayUndoBookmark: MutableStateFlow<Boolean> = MutableStateFlow(false)
val shouldDisplayUndoBookmark: StateFlow<Boolean> = _shouldDisplayUndoBookmark.asStateFlow()If you agree with this approach, I'd like to proceed with submitting a pull request. 😊
Additional context
No response
Code of Conduct
- I agree to follow this project's Code of Conduct