我正在 onCreate
内执行一个协程来进行 API 调用。
我想在执行 onCreateView
之前等待 api 响应,因为我正在使用答案来显示信息。
通常,我用它来等待工作
GlobalScope.launch(Dispatchers.Main) {
job!!.join()
//call to next method
}
但我不能自己调用 onCreateView
。它在我的片段的生命周期过程中被调用。
所以使用这个,我得到了 NullPointerException
,因为我还没有从我的 API 中得到答案。
我也使用 runBlocking
。但它冻结了 UI,我在 API 调用期间使用了加载器动画
现在,我正在使用这个畸变:
while(!jobGet!!.isCompleted) {}
它有效,但我不能离开那个......
这是我的代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bundle = this.arguments
if (bundle != null && bundle.containsKey("eventSuggestionDto")) {
val eventSuggestionDto = bundle.getSerializable("eventSuggestionDto") as EventSuggestionDto
(activity as MainActivity).startAnim()
jobGet = CoroutineScope(Dispatchers.IO).launch {
getEvent(eventSuggestionDto.objectId)
}
while(!jobGet!!.isCompleted) {}
(activity as MainActivity).stopAnim()
}
}
那么如何替换while(!jobGet!!.isCompleted) {}
?