我正在尝试使用改造的get请求从服务器获取数据,在ViewModel中,我发起了请求,该请求的OnResponse方法显示已成功从服务器检索数据,但片段中的观察者未更新。我正在共享下面的代码。
RETROFIT API调用
fun getGenres(application: Context,callback:(List<Genre>)->Unit){
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 {
callback(this?.genres!!) }
Toast.makeText(application, "success: ${response.body()?.genres?.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() {
ApiFunctions.getGenres(getApplication<Application>(), { l -> listOfCategory.value = l } )
listOfCategory.postValue(listOfCategory.value)
}
}
我认为问题出在这一堂课,但我想不出来。
**片段等级**
class MainFragment : Fragment() {
private lateinit var viewModel: CategoryViewModel
private lateinit var binding: FragmentMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(CategoryViewModel::class.java)
viewModel.getistOfCategory()
}
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.listOfCategory.observe(this,
Observer { list ->
Toast.makeText(
context,
"Data Changed" + list?.size,
Toast.LENGTH_LONG
).show()
})
return myView
}
我想要的是,当从服务器检索到新值时,应将其保存在ViewModel类的LiveData中,并且片段应成功观察到它们。