streetsofboston
10/24/2019, 5:41 AM@Model
class?Cody Engel
10/24/2019, 5:42 AMmaster
though 😅
abstract class ComposeViewModel<T> : ViewModel() {
// This should return a class annotated with @Model
abstract val model: T
}
@Model
data class Name(var name: String = "Android")
class NameViewModel : ComposeViewModel<Name>() {
override val model: Name = Name()
}
streetsofboston
10/24/2019, 5:43 AMstreetsofboston
10/24/2019, 5:44 AM@Model
won't work?Cody Engel
10/24/2019, 5:45 AMCompose
though I’d like to be done with LiveData
thoughCody Engel
10/24/2019, 5:46 AMstreetsofboston
10/24/2019, 5:50 AM@Model
type need to be held by a LiveData
type? I haven't tried it, but couldn't the ViewModel just instantiate a proper val
instance of that @Model
type and have the ViewModel's methods modify that property's properties (that are observed by the @Model
annotation)?Cody Engel
10/24/2019, 5:52 AMCody Engel
10/24/2019, 5:53 AMViewModel
with @Model
would just round things out I think…
abstract class ComposeViewModel<T> : ViewModel() {
// This should return a class annotated with @Model
abstract val model: T
}
@Model
data class Name(var name: String = "Android")
class NameViewModel : ComposeViewModel<Name>() {
override val model: Name = Name()
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
setContent {
HelloForm(viewModel.model)
}
}
}
@Composable
fun HelloForm(name: Name) = MaterialTheme {
Column(modifier = Spacing(16.dp)) {
Greeting(name = name.name)
TextField(
value = name.name,
onValueChange = {
name.name = it
}
)
Button(text = "New Name")
}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!", modifier = Spacing(top = 16.dp, bottom = 16.dp))
}
Cody Engel
10/24/2019, 5:54 AMButton
no longer does anything 😅streetsofboston
10/24/2019, 6:03 AM@Model
.
Say, in your onValueChange
you'd wan to invoke a method on your ViewModel (not just change the Name's name
); then you'd have to pass both the ViewModel and its @Model
property into the HelloForm()
function or just pass the ViewModel and always write viewModel.name
to access the @Model
instance...Luca Nicoletti
10/24/2019, 7:47 AMViewModel
in the first place?streetsofboston
10/24/2019, 2:51 PMLuca Nicoletti
10/24/2019, 2:53 PMstreetsofboston
10/24/2019, 2:56 PMCody Engel
10/24/2019, 3:29 PMCody Engel
10/24/2019, 3:31 PM