LiveData不会发出所需值

问题描述 投票:0回答:2

我创建了这样的实时数据:

val authTokenLiveData: LiveData<String?> = liveData {
    emit(accountManager.myAuthToken())
}

我正在观察它:

accountViewModel.authTokenLiveData.observe(this) {
    toast("Token is $it")
    if(it == null) goToLogin()
}

[起初效果很好,我烘烤了令牌,但是注销后删除令牌,使得令牌为null,根据观察者,我不应该登录。

[当令牌变为authTokenLiveData时如何确保null发出null,以便观察者允许我进入登录屏幕?

android android-livedata
2个回答
0
投票
   // LiveData object is usually stored within a ViewModel 
    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }


   // updating the live data object 
   // using setValue(T) or postValue(T)
   button.setOnClickListener {
          val anotherName = "John Doe"
          model.currentName.setValue(anotherName)
      }

  // Observe LiveData Object
  // Use the 'by viewModels()' Kotlin property delegate
  // from the activity-ktx artifact
private val model: NameViewModel by viewModels()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Other code to setup the activity...

    // Create the observer which updates the UI.
    val nameObserver = Observer<String> { newName ->
        // Update the UI, in this case, a TextView.
        nameTextView.text = newName
    }

    // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
    model.currentName.observe(this, nameObserver)
}

0
投票

LiveData中创建ViewModel,例如:

val authToken: MutableLiveData<String?> by lazy {
    MutableLiveData<String?>()
}

像[[0]一样观察LiveData

Activity

像[[0]一样观察viewModel.authToken.observe(viewLifecycleOwner, Observer { toast("Token is $it") if(it == null) goToLogin() })

LiveData

Fragment传递到viewModel.authToken.observe(viewLifecycleOwner, Observer { toast("Token is $it") if(it == null) goToLogin() }) 。然后将数据从ViewModel发送到AccountManager,例如:

LiveData

您将获得最新数据到您的观察者区。

© www.soinside.com 2019 - 2024. All rights reserved.