kotlin - 来自改造请求的 LiveData 响应问题
问题描述
有人能解释一下为什么我的 MutableLiveData 总是“null”吗?在另一个项目中,我不喜欢这里并且它工作。也许我是盲人之类的,我看不到简单的错误之类的。
class HomeViewModel : ViewModel() {
val mutableLiveData = MutableLiveData<String>()
fun setString(word: String) {
mutableLiveData.value = word
}
fun getString(): LiveData<String> {
return mutableLiveData
}
}
class HomeFragment : Fragment() {
lateinit var homeViewModel: HomeViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val root = inflater.inflate(R.layout.fragment_home, container, false)
val textView: TextView = root.findViewById(R.id.text_home)
homeViewModel = activity!!.run {
ViewModelProviders.of(this).get(HomeViewModel::class.java)
}
homeViewModel.getString().observe(this, Observer<String>{
t -> textView.text = t
})
AsyncTaskAllInvoices(ApiConnection().connectionApiInitialize(), this).execute()
return root
}
}
class AsyncTaskAllInvoices(val apiService: ApiService, val activity: HomeFragment) : AsyncTask<Any, Any, Any>() {
override fun doInBackground(vararg params: Any?) {
ApiConnection().showAllInvoices(apiService, activity)
}
}
class ApiConnection: Fragment() {
private lateinit var homeViewModel: HomeViewModel
fun connectionApiInitialize(): ApiService {
val retrofit = Retrofit.Builder()
.baseUrl(LocalVariables.baseApiURl)
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(ApiService::class.java)
}
fun showAllInvoices(apiService: ApiService, activity: Fragment) {
homeViewModel = activity!!.run {
ViewModelProviders.of(activity).get(HomeViewModel::class.java)
}
val call = apiService.getAllInvoices()
call.enqueue(object: Callback<List<InvoiceResponse>> {
override fun onFailure(call: Call<List<InvoiceResponse>>?, t: Throwable?) {
Log.v("parser", "call onFailure")
}
override fun onResponse(call: Call<List<InvoiceResponse>>?, response: Response<List<InvoiceResponse>>?) {
if (response != null) {
if (response.isSuccessful()) {
homeViewModel.setString(response!!.body()!![0].driver)
Log.v("parser", homeViewModel.getString().value)
}
}
}
})
}
}
当我使用时:
Log.v("parser", homeViewModel.getString().value)
在 onResponse 中我得到了应该是的值,但它没有在我的 FragmentActivity 中更新。有任何想法吗?
谢谢 :_)
解决方案
推荐阅读
- entity-framework - 如何修复 .Net Core POST 操作中的 400 Bad Request 错误?
- c# - 在 C# 控制台应用程序中,我将如何为二十一点游戏中的纸牌创建“图像”?
- netlogo - Netlogo gis(道路网络):将距离(特征)从 gis 复制到 netlogo 中的道路链接
- c# - 如何将 XML Choice 反序列化为正确的复杂类型
- magento2 - Magento 2 管理员忘记密码电子邮件密码链接未显示
- c# - Task.Run() & Task.Delay() 在一段时间后终止
- oauth-2.0 - IdentityServer4:如何显示外部提供商同意屏幕?
- c++ - 多维数组由于某种原因不改变函数中的元素
- stm32 - 我们可以通过 UART 端口从 STM32F103C8T6 发送 Quectel M66 的命令吗?
- c - 在 Linux 上以编程方式永久设置 DNS / 名称服务器