简体   繁体   中英

Suspend a running Coroutine

I can suspend a coroutine by calling suspendCoroutine<String> { cont -> continuation = cont } inside a coroutine but how do i suspend it from outside of coroutine and get a continuation back to resume it later?

Edit:

The job of coroutine is to receive json messages from server using jackson streaming api and store them using sqlite and also notify activities of new message if callbacks are not null (activities are running)

Now when the service (which holds coroutine) is already running and updating database, if an activity connects to it, i want activity to first fetch all the messages from database and then continue receiving new messages from service.

Problem:

  • If i let coroutine run while activity is synchronizing messages from database, new messages might not be synchronized fully/properly or end up in the middle of old messages, reason i want coroutine to be paused until synchronization is completed.

  • I cannot check if i should suspendCoroutine before jackson starts waiting for new message, it will quickly pass this condition.

  • I cannot check if i should suspendCoroutine while jackson is waiting for new messages from network (blocked on read), it cannot be done.

  • I cannot check if i should suspendCoroutine after jackson has received a message because then I will have to wait for a new message to start synchronization.

Edit2:

I think best solution is to just start synchronization and add a check if activity is already synchronizing after data is received and before any callbacks are made or data is stored to database , that way, coroutine can freely block on read and not insert new data until activity is finished synchronizing.

I assume you are opening two different coroutines instead of one, which gives you 0 control to which one runs first:

You could just do all the work inside one coroutine and the execution of it would be as imperative programming is:

someScope.launch(someDispatcher){
  val dataFromDb = fethDbData()
  if(dataFromDb.size == expectedSizeOrSomething){
     //start api call
     val apiResponse = response.fetchNetworkData()
     if (response.isSuccessful){
       parsePerhaps()
       insertNewDataToDatabase()
      }
   }
}

That should be it, by the description you make.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM