JETPACK组成了来自可组合的班级的实例化类

发布于 2025-02-12 03:06:34 字数 1213 浏览 0 评论 0原文

我有以下逻辑类,

class Logic(){
    private val state: MyViewModel = MyViewModel()

    
    @Composable
    fun PublicComposable(){
      Text("My public composable")
    }

    
    fun setSomething(value:String){
      state.setSomething(value)
    }

    fun getSomething(){
      return state.getSomething()
    }
}

我有我的ViewModel,UI不应该可以访问,而仅适用于逻辑类

class MyViewModel():ViewModel(){

    private val _capturedCard: MutableLiveData<String> = MutableLiveData("Intial Value")
    val capturedCard: LiveData<String> = _capturedCard

    fun setSomething(value:String){
      _capturedCard.value = value
    }

    fun getSomething():String{
      return capturedCard.value
    }

}

,然后我的组合可供我称为:

@Composable
fun Content(){
    val myclass = Logic()
    myclass.PublicComposable()

    Text("Updated Value")

    Button(onClick = {myclass.setSomething("New Value")}){
      Text("Set Something")
    }

    Text("${myclass.getSomething()}")

output

Text("Initial Value")

Instead of 

Text("New Value")

我在这里做错了什么,因为我不希望查看模型在Compose App UI上可用,而只能仅在logic()类中存在。

I have my following logic class

class Logic(){
    private val state: MyViewModel = MyViewModel()

    
    @Composable
    fun PublicComposable(){
      Text("My public composable")
    }

    
    fun setSomething(value:String){
      state.setSomething(value)
    }

    fun getSomething(){
      return state.getSomething()
    }
}

I have my ViewModel which should not be accessible to the UI but only to the Logic class

class MyViewModel():ViewModel(){

    private val _capturedCard: MutableLiveData<String> = MutableLiveData("Intial Value")
    val capturedCard: LiveData<String> = _capturedCard

    fun setSomething(value:String){
      _capturedCard.value = value
    }

    fun getSomething():String{
      return capturedCard.value
    }

}

Then I have my composable which I call as follows:

@Composable
fun Content(){
    val myclass = Logic()
    myclass.PublicComposable()

    Text("Updated Value")

    Button(onClick = {myclass.setSomething("New Value")}){
      Text("Set Something")
    }

    Text("${myclass.getSomething()}")

Output

Text("Initial Value")

Instead of 

Text("New Value")

What am I doing wrong here because I don't want the view model to be available on the compose app ui but to be present on the Logic() class only.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文