how to change an Int value using ViewModel - android

How to change an Integer Value of a composable from another composable using viewModel so that when We navigate to That Composable/screen we should see the changed Value
private var _amt = mutableStateOf<Int>(5)
var amt: MutableState<Int> = _hanging
fun changeHangingToFortyFive(){
amt.value = 45
}

You can add private set, instead of having private _variable and public variable:
class MyViewModel: ViewModel() {
var amt by mutableStateOf(5)
private set
fun updateAmt(newValue: Int) {
amt = newValue
}
}
And in your composable.
val viewModel: MyViewModel = viewModel()
val value = viewModel.amt
//To update
viewModel.updateAmt(newValue)

Ideally you should be hoisting the viewModel in a parent composable (probably a NavHost) and pass an lambda expression to update the value of the view model from the child composable.
Example: Passing a callback to some child composable to set the value of view model from there.
#Composable
fun parent(viewModel: ViewModel){
childComposable(onValueChange=
{changedValue -> viewModel.updateAmt(changedValue}
)
}

Related

How to pass parameter to my hilt viewmodel from jetpack compose

I have a composable with viewmodel and I want to pass an id from the composable to the viewmodel.
My composable is:
#Composable
fun HttpRequestScreen(
viewModel: HttpRequestViewModel = hiltViewModel(),
id: String = EMPTYUUID,
onClick: (String, String, Int) -> Unit // respond, request Function: 1 - send request, 2 - edit request
) {
I have the id from a different screen and I want to pass it to my Hilt viewmodel.
Assuming that you have followed the documentation for compose navigation, you can find your parameter here:
#HiltViewModel
class RouteDetailsViewModel #Inject constructor(
private val getRouteByIdUC: GetRouteByIdUC,
private val savedStateHandle: SavedStateHandle
): ViewModel() {
private val routeId = savedStateHandle.get<String>("your-param-name") // for example String in my case
}
You will need to think in a Unidirectional Data Flow pattern, where events flow up and state flows down. For this, you need to expose some sort of state from your viewmodel that sends down the state of the request to the Composable as an observable state.
Your viewmodel could look like this.
class HttpRequestViewModel: ViewModel() {
private val _httpResponse = mutableStateOf("")
val httpResponse: State<String> = _httpResponse
fun onHttpRequest(requestUrl: String) {
//Execute your logic
val result = "result of your execution"
_httpResponse.value = result
}
}
Then in your Composable, you can send events up by calling the ViewModel function on the button click like so
#Composable
fun HttpRequestScreen(viewModel: HttpRequestViewModel) {
val state by viewModel.httpResponse
var userInput = remember { TextFieldValue("") }
Column {
Text(text = "Http Response = $state")
}
BasicTextField(value = userInput, onValueChange = {
userInput = it
})
Button(onClick = { viewModel.onHttpRequest(userInput.text) }) {
Text(text = "Make Request")
}
}
I hope that points you in the right direction. Good luck.

How can we save and restore state for Android StateFlow?

We can create LiveData or StateFlow in a similar way as below
val _liveData = MutableLiveData(0)
val _stateFlow = MutableStateFlow(0)
But In LiveData, we can ensure the data is saved and restored by using
val _liveData: MutableLiveData<Int> = savedStateHandle.getLiveData("Key", 0)
For StateFlow, is there a way (or API) to keep the last value and restore it, like what we have in LiveData?
I use the conventional way in ViewModel to store and restore the value
private val _stateFlow = MutableStateFlow(
savedStateHandle.get("key") ?: InitialValue
)
And when setting the value
_stateFlow.value = ChangeValue
savedStateHandle.set("key", ChangeValue)
Not ideal, but at least we have a way to save the latest value.
And thanks to https://www.reddit.com/user/coffeemongrul/, who provided a proposal to wrap it around with a class as per https://www.reddit.com/r/androiddev/comments/rlxrsr/in_stateflow_how_can_we_save_and_restore_android/
class MutableSaveStateFlow<T>(
private val savedStateHandle: SavedStateHandle,
private val key: String,
defaultValue: T
) {
private val _state: MutableStateFlow<T> =
MutableStateFlow(savedStateHandle.get<T>(key) ?: defaultValue)
var value: T
get() = _state.value
set(value) {
_state.value = value
savedStateHandle.set(key, value)
}
fun asStateFlow(): StateFlow<T> = _state
}
Can you try this? I haven't tried it yet but I think it might work.
private val _stateFlow: MutableStateFlow<Int>?
get()= savedStateHandle.get<MutableStateFlow<Int>>("KEY")
I can propose one more solution. A simple extension that will update SavedStateHandle once MutableStateFlow will be updated.
fun <T> SavedStateHandle.getMutableStateFlow(
scope: CoroutineScope,
key: String,
initialValue: T
): MutableStateFlow<T> {
return MutableStateFlow(get(key) ?: initialValue).apply {
scope.launch(Dispatchers.Main.immediate) {
this#apply.collect { value ->
set(key, value)
}
}
}
}

Jetpack compose data store keeps recomposing screen

I'm migrating from Shared preference to data store using jetpack compose. everything works fine (data is saved and can be retreated successfully). However, whenever a Data is retrieved, the composable keeps on recomposing endlessly. I'm using MVVM architecture and below is how I have implemented data store.
Below is declared in my AppModule.kt
App module in SingletonComponent
#Provides
#Singleton
fun provideUserPreferenceRepository(#ApplicationContext context: Context):
UserPreferencesRepository = UserPreferencesRepositoryImpl(context)
Then here's my ViewModel:
#HiltViewModel
class StoredUserViewModel #Inject constructor(
private val _getUserDataUseCase: GetUserDataUseCase
): ViewModel() {
private val _state = mutableStateOf(UserState())
val state: State<UserState> = _state
fun getUser(){
_getUserDataUseCase().onEach { result ->
val name = result.name
val token = result.api_token
_state.value = UserState(user = UserPreferences(name, agentCode, token, balance))
}.launchIn(viewModelScope)
}}
Finally, Here's my Repository Implementation:
class UserPreferencesRepositoryImpl #Inject constructor(
private val context: Context
): UserPreferencesRepository {
private val Context.dataStore by preferencesDataStore(name = "user_preferences")
}
private object Keys {
val fullName = stringPreferencesKey("full_name")
val api_token = stringPreferencesKey("api_token")
}
private inline val Preferences.fullName get() = this[Keys.fullName] ?: ""
private inline val Preferences.apiToken get() = this[Keys.api_token] ?: ""
override val userPreferences: Flow<UserPreferences> = context.dataStore.data.catch{
// throws an IOException when an error is encountered when reading data
if (it is IOException) {
emit(emptyPreferences())
} else {
throw it
}
}.map { preferences ->
UserPreferences(name = preferences.fullName, api_token = preferences.apiToken)
}.distinctUntilChanged()
I don't know what causes the composable to recompose. Below Is the composable:
#Composable
fun LoginScreen(
navController: NavController,
userViewModel: StoredUserViewModel = hiltViewModel()
) {
Log.v("LOGIN_SCREEN", "CALLED!")
userViewModel.getUser()
}
If anyone can tell me where I've done wrong please enlighten me. I have tried to change the implementation in AppModule for UserPreferencesRepository but no luck.
Below is UseState.kt which is just a data class
data class UserState(
val user: UserPreferences? = null
)
Below is UserPreferences.kt
data class UserPreferences(val name: String, val api_token: String)
I also faced such problem. The solution was became to navigate with LauchedEffect in composable.
before:
if (hasFlight) {
navController.navigate(Screen.StartMovingScreen.route)
}
after:
if (hasFlight) {
LaunchedEffect(Unit) {
navController.navigate(Screen.StartMovingScreen.route)
}
}
This is expected behaviour: you're calling getUser on each recomposition.
#Composable function is a view builder, and should be side-effects free.
Instead you can use special side effect function, like LaunchedEffect, which will launch job only once, until it's removed from view tree or key argument is changed:
LaunchedEffect(Unit) {
userViewModel.getUser()
}
But this also will be re-called in case of configuration change, e.g. screen rotation. To prevent this case, you have two options:
Call getUser inside view model init: in this case it's guarantied that it's called only once.
Create some flag inside view model to prevent redundant request.
More info about Compose side effects in documentation.

Why my Android ViewModel cannot persistent data?

I`m programing with Jetpack Compose.
I request data from net and save it into a ViewModel in a Composable,
but when I want to use the data in other Composable, the ViewModel returns null
// ViewModel:
class PartViewModel : ViewModel() {
private val mPicRepository: PicRepository = PicRepository()
private val _partsResult: MutableLiveData<PicResp> = MutableLiveData()
val partsResilt: LiveData<PicResp> get() = _partsResult
fun getPartsFromImage(id: Long) {
mPicRepository.getCloudPic(id, _partsResult)
}
}
// Composable which request data
#Composable
fun PagePhotoDetail(imageId: Long, navController: NavHostController) {
val vm: PartViewModel = viewModel()
vm.getPartsFromImage(imageId)
partsState.value?.data?.let {
Logger.d(it.parts) // this log show correct data
}
}
// Composable which use data
#Composable
fun PagePartListFromImage(navController: NavHostController) {
val vm: PartViewModel = viewModel()
Logger.d(vm.partsResilt.value) // this log cannot get data and show null
}
You are creating two different instances of your viewmodel. You need to initialise the viewmodel like val vm by viewmodels<PartViewModel>
Then pass this viewmodel as a parameter inside the Composable. You're done!
Well, if you still wish to initialise it inside a Composable, you can use val vm by viewmodel<PartViewModel>.
viewModel<> instead of viewModels<>

How to build a live data based on lateinit property?

I have a property with late initialization.
Now I want to provide a live data which does not emit anything until the property is initialized completely.
How to do this in proper Kotlin way?
class SomeConnection {
val data: Flow<SomeData>
...
class MyViewModel {
private lateinit var _connection: SomeConnection
// private val _connection: CompletableDeferred<SomeConnection>()
val data = _coonection.ensureInitilized().data.toLiveData()
fun connect(){
viewModelScope.launch {
val conn = establishConnection()
// Here I have to do something for the call ensureInitilized to proceed
}
}
private suspend fun establishConnection(){
...
}
Declare a MutableLiveData emitting values of type SomeConnection and a corresponding LiveData.
private val _connectionLiveData = MutableLiveData<SomeConnection>()
val connectionLiveData: LiveData<SomeConnection> = _connectionLiveData
Then assign value to _connectionLiveData when _connection is initialized:
if (::_connection.isInitialized()) _connectionLiveData.value = _connection
(or _connectionLiveData.postValue(_connection) if your code works concurrently)
Now observe this LiveData in another place in code, I'll use fragment here for the sake of example:
override fun firstOnViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel.connectionLiveData.observe(this, ::sendData)
}
Then send the desired data via the corresponding view model method

Categories

Resources