我正在尝试学习如何使用modelViewScope和liveData从挂起的db调用中获取数据,并使用收集的数据将数据从片段绑定到视图,以消除设置视图的样板代码。我没有从代码中得到任何错误,但没有得到我在视图中设置的值。
TextView文本将显示@ {viewModel.listingDetails.locationAddress而不是LiveData信息。
我想念什么?或我应该编辑什么以获得适当的值?
我的列表存储库代码:
interface ListingRepository {
...
suspend fun getListingDetailsById(id: String): ListingDetailEntries
}
我的片段代码:
class ListingDetailsFragment : ScopedFragment(), KodeinAware {
override val kodein by closestKodein()
private val viewModelFactoryInstanceFactory: ((String) -> ListingDetailsViewModelFactory) by factory()
private lateinit var viewModel: ListingDetailsViewModel
private val args: ListingDetailsFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel = ViewModelProvider(this, viewModelFactoryInstanceFactory(args.id))
.get(ListingDetailsViewModel::class.java)
val binding: ListingDetailsFragmentBinding =
DataBindingUtil.inflate(inflater, R.layout.listing_details_fragment, container, false)
binding.lifecycleOwner = this
binding.viewModel = viewModel
return binding.root
}
我的ViewModel代码:
class ListingDetailsViewModel(
private val id: String,
private val listingRepository: ListingRepository
) : ViewModel() {
var listingDetails = liveData(Dispatchers.IO) {
val listing = listingRepository.getListingDetailsById(id)
emit(listing)
}
}
我的布局代码:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.example.testsentia.ui.detail.ListingDetailsViewModel" />
</data>
<TextView
...
android:text="@{viewModel.listingDetails.locationAddress" />
</layout>
从Fragment观察时,我得到了所需的值,所以我知道存在数据,只是不知道如何正确执行此操作。
答案 0 :(得分:1)
<TextView
...
android:text="@{viewModel.listingDetails.locationAddress" /> //You're missing closing brace here