Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

kotlin - How to wait for coroutine launched in IO thread in destroyed fragment?

I have 2 fragments. The first is a list of tasks and the second is a fragment that contains information about clicked task. Let`s imagine we have task with displayed name 'hello'. When i click on it, it navigates to fragment 2 and displays 'hello' and other data like date, description etc. In this fragment i have a method that launches a coroutine in IO thread and sends patch request to server to edit task name. It is called when fragment is paused (it can signify exiting from app, returning to first fragment, pressing system button home).

So the scheme is: click on task -> open fragment with full data -> change name -> click back button -> launch coroutine in IO -> destroy fragment 2 and navigate to fragment 1 with task's list -> make get request for new data -> show data.

The problem is when it makes get request for new data, it takes old data because coroutine from destroyed fragment 2 has not completed yet. Processing: patch req -> destroy fragment -> open frag 1 -> get req -> receive response from get -> patch req completed -> show old data

How can i wait for patch request ending launched in destroeyed fragment 2 from my fragment 1?? I have just discovered one solution: using runBlocking in viewModelscope, but this will block main thread

question from:https://stackoverflow.com/questions/65894093/how-to-wait-for-coroutine-launched-in-io-thread-in-destroyed-fragment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...