https://kotlinlang.org logo
Title
d

dave08

11/26/2019, 1:29 PM
I'm not sure how immediate works, doesn't it run on the caller's thread and Hi would be printed before Finished... (maybe I have to add a
yield()
)?
g

gildor

11/26/2019, 1:51 PM
Immediate just avoid dispatching if it's main thread. Imagine that without immediate coroutine always does
<http://mainHandler.post|mainHandler.post> { work() }
and with immediate it will do
if (isMainThread) work() else post { work() }
But because you do delay (), it will always also do mainHandler.postDelay(::work, 30), just because it's only way for non blocking delay
If you want to do something on caller's thread you can use Unconfined
But what is exactly your use case for it?
d

dave08

11/26/2019, 1:56 PM
In the end, with immediate, does all the code in
launch
get run before the method exits, or can such code leak? I have a SyncAdapter that I need to use its service's lifecycleScope on
But I don't want work to leak
And runBlocking won't give me the Service's scope, so if Android kills the service, the task might leak
g

gildor

11/26/2019, 2:28 PM
It will leak if it will not be cancelled
Same as with other dispatcher
d

dave08

11/26/2019, 2:29 PM
That's why I want to use
lifecycleScope
with
launch
g

gildor

11/26/2019, 2:29 PM
Yes, make sense, I'm still didn't get your case
Do you launch something in a service?
d

dave08

11/26/2019, 2:30 PM
override fun onPerformSync(
			account: Account,
			bundle: Bundle,
			s: String,
			contentProviderClient: ContentProviderClient,
			syncResult: SyncResult
	) = coroutineScope.launch {

		syncEventTrigger.onSyncStart(context, syncResult)
				.onStart { i { "Sync Started" } }
				.onCompletion { i { "Sync Stopped" } }
				.collect()

    }.let { Unit }
Which Android runs in the context of a bound service
So I made that service into a
LifecycleService
that provides me with a
lifecycleScope
extension (from ktx)
But I'm afraid onPerformSync will exit before the tasks are finished in
launch
Then Android might unbind the Service and cancel all my tasks because it thinks I'm finished already
That's why I wondered that maybe immediate maybe stops onPerformSync from exiting since it's running on it's thread
g

gildor

11/26/2019, 2:39 PM
If so, just cancel scope on service.onDestroy
d

dave08

11/26/2019, 2:45 PM
I don't understand how that would help? That's handled by
lifecycleScope
automatically I think, the problem knowing whether onPerformSync exits before the work is all done...
Unless you mean to use runBlocking, and just handle the cancelling myself?
(which might be a bit harder from an adapter using a bound service...)