我的活动中的 ViewModel.Observe() 函数没有触发
Posted
技术标签:
【中文标题】我的活动中的 ViewModel.Observe() 函数没有触发【英文标题】:ViewModel.Observe() function in my activity doesn't trigger 【发布时间】:2020-09-08 13:37:33 【问题描述】:我有一个从 api 获取数据的类。我已经记录了我得到的结果,所以我确信正在获取数据。但是我的活动中的 viewModel.Observe() 应该检查我的 livedata 的变化并没有被触发。下面是我的代码
class PokemonOverviewModel():ViewModel()
private var pokemonIndividualData = MutableLiveData<PokemonIndividualDetails>()
fun getPokemonIndividualDataDetails(): LiveData<PokemonIndividualDetails>
return pokemonIndividualData
fun getPokemonIndividualDetails(id:String)
viewModelScope.launch
try
val pokemonIndividualResults = pokemonApi.retrofitService.getPokemonDetails(id)
Log.d("SUCCESSDETAILS", "$pokemonIndividualResults")
pokemonIndividualData.setValue(pokemonIndividualResults)
catch (e: Exception)
Log.d("FAILUREDETAILS", "$e")
调用 viewModel.Observe() 的 Activity 类
class PokemonDetails : AppCompatActivity()
lateinit var pokemonBinding: ActivityPokemonDetailsBinding
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
pokemonBinding = DataBindingUtil.setContentView(this,R.layout.activity_pokemon_details)
var height_details = pokemonBinding.heightDetails
var string = intent.getStringExtra("NUM")
PokemonOverviewModel().getPokemonIndividualDetails(string!!)
Log.d("GOTTENURL", "$string")
val viewGotten = ViewModelProvider(this).get(PokemonOverviewModel::class.java)
viewGotten.getPokemonIndividualDataDetails().observe(this, Observer
Toast.makeText(this, "DATA CHANGED", Toast.LENGTH_LONG).show()
)
【问题讨论】:
【参考方案1】:我发现我两次初始化了我的视图模型。观察函数只是观察第二个实例
class PokemonDetails : AppCompatActivity()
lateinit var pokemonBinding: ActivityPokemonDetailsBinding
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
pokemonBinding = DataBindingUtil.setContentView(this,R.layout.activity_pokemon_details)
var height_details = pokemonBinding.heightDetails
var string = intent.getStringExtra("NUM")
// height_details.text = PokemonDetailsList.getList().toString()
Log.d("GOTTENURL", "$string")
val viewGotten = ViewModelProvider(this).get(PokemonOverviewModel::class.java)
//I added this line
viewGotten.getPokemonIndividualDetails(string!!)
viewGotten.getPokemonIndividualDataDetails().observe(this, Observer
Toast.makeText(this, "DATA CHANGED", Toast.LENGTH_LONG).show()
height_details.text = it.height
)
【讨论】:
哦,是的,我没有注意到,初始化是在`PokemonOverviewModel()`下面再次完成...以上是关于我的活动中的 ViewModel.Observe() 函数没有触发的主要内容,如果未能解决你的问题,请参考以下文章