在ViewModel中从服务器获取数据后,LiveData Observer不会更新UI

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

我正在尝试使用改造的get请求从服务器获取数据,在ViewModel中,我发起了请求,该请求的OnResponse方法显示已成功从服务器检索数据,但片段中的观察者未更新。我正在共享下面的代码。

RETROFIT API调用

 fun getGenres(application: Context): MutableLiveData< List<Genre> >{
        val baseURL = "https://listen-api.listennotes.com/"
        var genreList: MutableLiveData<List<Genre>> =MutableLiveData()
        val logging = HttpLoggingInterceptor()
//      set your desired log level
        logging.level = HttpLoggingInterceptor.Level.BODY

        val httpClient = OkHttpClient.Builder()
//      add your other interceptors …
//      add logging as last interceptor
        httpClient.addInterceptor(logging)

        val gson = GsonBuilder()
            .setLenient()
            .create()

        val retrofit = Retrofit.Builder()
            .baseUrl(baseURL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(httpClient.build())
            .build()

        val api: ApiFunctions = retrofit.create(ApiFunctions::class.java)



        val call: Call<PodcastGetCategoryResponse> = api.getGenres()

        call.enqueue(object : Callback<PodcastGetCategoryResponse> {
            override fun onFailure(call: Call<PodcastGetCategoryResponse>, t: Throwable) {

                Toast.makeText(application, "failure" + t.stackTrace, Toast.LENGTH_SHORT).show()

            }

            override fun onResponse(
                call: Call<PodcastGetCategoryResponse>,
                response: Response<PodcastGetCategoryResponse>
            ) {

                response.body().apply {
                   genreList.value= this?.genres!!
                }
                Toast.makeText(application, "success: ${genreList.value?.size}", Toast.LENGTH_SHORT).show()

            }

        })

        return genreList;
    }

这将成功运行,并从服务器检索类型列表。

VIEWMODEL CLASS

class CategoryViewModel(application: Application) : AndroidViewModel(application) {
private val rootJob = SupervisorJob()

private val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + rootJob

 var listOfCategory: MutableLiveData<List<Genre>> = MutableLiveData()

init {
    getistOfCategory()
}

// this method is responsible for retrieving data from the result of the API call method using a coroutine.

fun getistOfCategory(): {
    CoroutineScope(coroutineContext).launch() {
      listOfCategory =   ApiFunctions.getGenres(getApplication<Application>())
    }

    }

}

我认为问题出在这一堂课,但我想不出来。

**片段等级**

class MainFragment : Fragment() {
private lateinit var viewModel: CategoryViewModel
private lateinit var binding: FragmentMainBinding


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    binding =DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
    var myView: View = binding.root


    viewModel = ViewModelProviders.of(this).get(CategoryViewModel::class.java)

    viewModel.listOfCategory.observe(this,
        Observer { list ->
            Toast.makeText(
                context,
                "Data Changed" + list?.size,
                Toast.LENGTH_LONG
            ).show()
        })

    return myView
}

我想要的是,当从服务器检索到新值时,应将其保存在ViewModel类的LiveData中,并且片段应成功观察到它们。

android kotlin mvvm android-livedata android-viewmodel
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.