Created
September 6, 2022 14:34
-
-
Save GibsonRuitiari/7643fa420006e8b8499f28e1ec7f5346 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ciru.practice | |
import androidx.lifecycle.ViewModel | |
import kotlinx.coroutines.flow.MutableStateFlow | |
import kotlinx.coroutines.flow.StateFlow | |
import kotlinx.coroutines.flow.update | |
/** | |
* This is the shared view model, that will be shared by the two composables (boo and bae) [honestly change the names] | |
*/ | |
class LoginViewModel : ViewModel(){ | |
/** | |
* This represents our state I am using '_' to represent/show that it is an internal state | |
* Whatever the user types will be put in LoginData and then the _loginData will be updated to the current login data | |
* simply put | |
* when user types email,password and username then he/she presses login button several things will happen | |
* 1. A new LoginData() object will be created | |
* 2. when [setUserDetails] will be invoked, the newly created LoginData() object will be passed into the function | |
* 3. our internal state [_loginData] will reference the newly created object/the LoginData object held by | |
* [_loginData] will be modified to represent the newly created LoginData() object. | |
* I honestly hope this makes sense. | |
*/ | |
private val _loginData = MutableStateFlow<LoginData>(LoginData.EMPTY) | |
val loginData:StateFlow<LoginData> | |
get() = _loginData | |
fun setUserDetails(loginData: LoginData){ | |
println("logging details: ${loginData.password},${loginData.username}, ${loginData.email}") | |
_loginData.update { | |
it.copy(email = loginData.email, username = loginData.username, | |
password = loginData.password) } | |
} | |
} | |
// class ViewModelA:ViewModel(){ | |
// private val _data = MutableStateFlow("") | |
// val data:StateFlow<String> | |
// get() = _data | |
// fun setData(newData:String){ | |
// // or you can use _data.update{ } | |
// _data.value = newData | |
// } | |
// } | |
// // inject your view model instance into your composables in your activitiy's onCreate | |
// @Composable | |
// fun ScreenB(sharedViewModel:ViewModel){ | |
// val data = sharedViewModel.data.collectAsState(initial="") | |
// // do something with it | |
// } | |
// @Composable | |
// fun ScreenA(sharedViewModel:ViewModel){ | |
// sharedViewModel.setData("data") | |
// } | |
//} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment