How to call suspend function from Service Android? - kotlin

How to provide scope or how to call suspend function from Service Android?
Usually, activity or viewmodel provides us the scope, from where we can launch suspend but there is no similar thing in Service

You can create your own CoroutineScope with a SupervisorJob that you can cancel in the onDestroy() method. The coroutines created with this scope will live as long as your Service is being used. Once onDestroy() of your service is called, all coroutines started with this scope will be cancelled.
class YourService : Service() {
private val job = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.IO + job)
...
fun foo() {
scope.launch {
// Call your suspend function
}
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
Edit: Changed Dispatchers.Main to Dispatchers.IO

SupervisorJob() (Kotlin GitHub) is a job that provides uniderectional cancellation; it allows for cancellations to propogate downwards only.
The SupervisorJob ... is similar to a regular Job with the only exception that cancellation is propagated only downwards. [KotlinLang.org]
Use case: You have a service that makes a log entry, checks settings, and depending on those settings goes ahead and performs some actions. Do you want all children jobs of the parent job (scope) to cancel if, for instance, a job run based on settings' values throws an exception? If not (i.e. you still want your logging and check for settings jobs to complete at the least) then you want to use the SupervisorJob(), or even supervisorScope (Kotlin GitHub) for 'scoped concurrency' [KotlinLang.org], as both provide unidirectional job cancellation - and in that case the provided answer works.
Coroutine Exception Handling - Supervision (KotlinLang.org)
However, there is a more direct solution that answers the question.
To provide to your service a scope with which to run coroutines (or suspending functions) that execute blocking code, you can simply create a new CoroutineScope() with an EmptyCoroutineContext:
(Snippet from CoroutineScope Documentation)
If the given context does not contain a Job element, then a default Job() is created. This way, cancellation or failure of any child coroutine in this scope cancels all the other children, just like inside coroutineScope block [Kotlin GitHub]
class YourClass : Extended() {
...
private val serviceScope: CoroutineScope( EmptyCoroutineContext )
...
private inner class ServiceHandler( looper: Looper ): Handler( looper ) {
override fun handleMessage( msg: Message ) {
super.handleMessage( msg )
serviceScope.launch {
try{
+ ...
} catch( e: Exception ) {
+ ...
} finally {
stopSelf( msg.arg1 )
}
}
}
}
override fun onCreate(){
+ ...
}
override fun onDestroy(){
/* In a service, unlike in an activity, we do not
need to make a call to the super implementation */
//super.onDestory()
serviceScope.cancel()
}
}

for me worked like that
import androidx.lifecycle.lifecycleScope
class ServiceLife : LifecycleService() {
private var supervisorJob = SupervisorJob(parent = null)
override fun onCreate() {
super.onCreate()
val serviceJob = lifecycleScope.launch {
//some suspend fun
}
supervisorJob[serviceJob.key]
supervisorJob.cancel()
}
}

Related

Do I need to warp the collectAsState() of a hot Flow with repeatOnLifecycle in #Composable?

I have read the article A safer way to collect flows from Android UIs.
I know the following content.
A cold flow backed by a channel or using operators with buffers such as buffer, conflate, flowOn, or shareIn is not safe to collect with some of the existing APIs such as CoroutineScope.launch, Flow.launchIn, or LifecycleCoroutineScope.launchWhenX, unless you manually cancel the Job that started the coroutine when the activity goes to the background. These APIs will keep the underlying flow producer active while emitting items into the buffer in the background, and thus wasting resources.
The Code A is from the official sample project.
The viewModel.suggestedDestinations is a MutableStateFlow, it's a hot Flow.
I don't know if the operation collectAsState() of hot Flow is safe in #Composable UI.
1: Do I need to use the Code just like Code B or Code C replace Code A for a hot Flow?
2: Is the operation collectAsState() of cold Flow safe in #Composable UI.
Code A
#OptIn(ExperimentalMaterialApi::class)
#Composable
fun CraneHomeContent(
onExploreItemClicked: OnExploreItemClicked,
openDrawer: () -> Unit,
modifier: Modifier = Modifier,
viewModel: MainViewModel = viewModel(),
) {
val suggestedDestinations by viewModel.suggestedDestinations.collectAsState()
...
}
#HiltViewModel
class MainViewModel #Inject constructor(
...
) : ViewModel() {
...
private val _suggestedDestinations = MutableStateFlow<List<ExploreModel>>(emptyList())
val suggestedDestinations: StateFlow<List<ExploreModel>>
}
Code B
class LocationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
...
}
}
}
}
Code C
#Composable
fun LocationScreen(locationFlow: Flow<Flow>) {
val lifecycleOwner = LocalLifecycleOwner.current
val locationFlowLifecycleAware = remember(locationFlow, lifecycleOwner) {
locationFlow.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
}
val location by locationFlowLifecycleAware.collectAsState()
...
}
collectAsState (Code A) is safe for any kind of Flow (cold/hot it doesn't matter). If you look at how collectAsState is implemented then you will see that it uses a LaunchedEffect deep down (collectAsState -> produceState -> LaunchedEffect)
internal class LaunchedEffectImpl(
parentCoroutineContext: CoroutineContext,
private val task: suspend CoroutineScope.() -> Unit
) : RememberObserver {
private val scope = CoroutineScope(parentCoroutineContext)
private var job: Job? = null
override fun onRemembered() {
job?.cancel("Old job was still running!")
job = scope.launch(block = task)
}
override fun onForgotten() {
job?.cancel()
job = null
}
override fun onAbandoned() {
job?.cancel()
job = null
}
}
which creates a coroutine scope and launches the task lambda once it enters the composition and cancels it automatically once it leaves the composition.
In Code A, viewModel.suggestedDestinations.collectAsState() (together with it's LaunchedEffect and it's coroutine scope) will be active as long as CraneHomeContent is being called by some other code. As soon as CraneHomeContent is stopped being called the LaunchedEffect inside of collectAsState() is canceled (and coroutine scope as well).
If it's called from multiple places then there will be multiple LaunchedEffects and thus multiple coroutine scopes.

Valid way to reuse coroutine scope?

So I have a class that has a lifecycle, containing a start() and an stop() function to start and stop the lifecycle. Now in that start() function I have to start a coroutine and in stop() I have to cancel it (The coroutine in start() runs infinitely until it is canceled, kinda like a socket listening for messages).
Because I would like a nice syntax to handle Coroutines I would like this class to implement CoroutineScope. The thing is that start() and stop() can be called multiple times.
My question is if this implementation is valid and does not contain any errors. The purpose is to make a reusable CoroutineScope.
class ReusableCoroutines() : CoroutineScope {
private var job = Job()
override val coroutineContext: CoroutineContext
get() = job
fun start() {
job = Job()
launch {
println("Started and running!")
while(true) {
}
}
}
fun stop() {
job.cancel()
println("Stoped")
}
}
Disclaimer: I wouldn't do this. You don't get much out of reusable objects unless you are creating them by the thousands every seconds. I'd just create throwaway classes that are initialized on creation (without a start function) and then cancelled when stop is called. That being said this might work:
class ReusableCoroutines(
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default)
) : CoroutineScope by scope {
private lateinit var job: Job
private var stopped: Boolean = false
private var started: Boolean = false
#Synchronized
fun start() {
require(stopped.not()) {
"Already stopped!"
}
require(started.not()) {
"Already started!"
}
job = launch {
println("Started and running!")
while (true) {
}
}
}
#Synchronized
fun stop() {
require(stopped.not()) {
"Already stopped!"
}
stopped = true
cancel()
println("Stopped")
}
}
So you need some synchronization #Synchronized to prevent start being called from multiple threads and ending up in an inconsistent state.
You also take the scope as a parameter so you can get Structured Concurrency with this. You can also add SupervisorJob to scope to prevent the parent from being canceled when you cancel this scope.

Ensure main JVM program will blow, even with launched with Kotlin Coroutines

I have a very simple Kotlin program like
fun main() {
val scope = CoroutineScope(Dispatchers.Default)
val job = scope.launch() { // I only check if this Job isActive later
withTimeout(2000) {
terminate(task)
}
}
}
private suspend fun terminate(task: Task): Nothing = suspendCoroutine {
throw IllegalAccessError("Task ${task.name} should honor timeouts!")
}
When terminate() is called I want my program to blow. I don't want to recover. However, I can't only see
Exception in thread "DefaultDispatcher-worker-2"
abc.xyz.mainKt$terminate$$inlined$suspendCoroutine$lambda$1: Task Robot should honor timeouts!
// More stacktrace ...
in logs, since Coroutines is "swallowing" this Exception.
Therefore, my question is : how would be a guaranteed way to blow my program when a timeout happens, with a design driven by Kotlin Coroutines?
How about this?
fun main() = runBlocking {
withTimeout(2000) {
terminate(task)
}
}

How can I guarantee to get latest data when I use Coroutine in Kotlin?

The Code A is from the project architecture-samples, you can see it here.
The updateTasksFromRemoteDataSource() is suspend function, so it maybe run asynchronously.
When I call the function getTasks(forceUpdate: Boolean) with the paramter True, I'm afraid that return tasksLocalDataSource.getTasks() will be fired before updateTasksFromRemoteDataSource().
I don't know if the Code B can guarantee return tasksLocalDataSource.getTasks() will be fired after updateTasksFromRemoteDataSource().
Code A
class DefaultTasksRepository(
private val tasksRemoteDataSource: TasksDataSource,
private val tasksLocalDataSource: TasksDataSource,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
override suspend fun getTasks(forceUpdate: Boolean): Result<List<Task>> {
// Set app as busy while this function executes.
wrapEspressoIdlingResource {
if (forceUpdate) {
try {
updateTasksFromRemoteDataSource()
} catch (ex: Exception) {
return Result.Error(ex)
}
}
return tasksLocalDataSource.getTasks()
}
}
private suspend fun updateTasksFromRemoteDataSource() {
val remoteTasks = tasksRemoteDataSource.getTasks()
if (remoteTasks is Success) {
// Real apps might want to do a proper sync, deleting, modifying or adding each task.
tasksLocalDataSource.deleteAllTasks()
remoteTasks.data.forEach { task ->
tasksLocalDataSource.saveTask(task)
}
} else if (remoteTasks is Result.Error) {
throw remoteTasks.exception
}
}
...
}
Code B
class DefaultTasksRepository(
private val tasksRemoteDataSource: TasksDataSource,
private val tasksLocalDataSource: TasksDataSource,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
override suspend fun getTasks(forceUpdate: Boolean): Result<List<Task>> {
// Set app as busy while this function executes.
wrapEspressoIdlingResource {
coroutineScope {
if (forceUpdate) {
try {
updateTasksFromRemoteDataSource()
} catch (ex: Exception) {
return Result.Error(ex)
}
}
}
return tasksLocalDataSource.getTasks()
}
}
...
}
Added Content
To Tenfour04: Thanks!
If somebody implement updateTasksFromRemoteDataSource() with lauch just like Code C, are you sure the Code C is return tasksLocalDataSource.getTasks() will be fired after updateTasksFromRemoteDataSource() when I call the function getTasks(forceUpdate: Boolean) with the paramter True?
Code C
class DefaultTasksRepository(
private val tasksRemoteDataSource: TasksDataSource,
private val tasksLocalDataSource: TasksDataSource,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
override suspend fun getTasks(forceUpdate: Boolean): Result<List<Task>> {
// Set app as busy while this function executes.
wrapEspressoIdlingResource {
if (forceUpdate) {
try {
updateTasksFromRemoteDataSource()
} catch (ex: Exception) {
return Result.Error(ex)
}
}
return tasksLocalDataSource.getTasks()
}
}
private suspend fun updateTasksFromRemoteDataSource() {
val remoteTasks = tasksRemoteDataSource.getTasks()
if (remoteTasks is Success) {
// Real apps might want to do a proper sync, deleting, modifying or adding each task.
tasksLocalDataSource.deleteAllTasks()
launch { //I suppose that launch can be fired
remoteTasks.data.forEach { task ->
tasksLocalDataSource.saveTask(task)
}
}
} else if (remoteTasks is Result.Error) {
throw remoteTasks.exception
}
}
}
New Added Content
To Joffrey: Thanks!
I think that the Code D can be compiled.
In this case, when forceUpdate is true, tasksLocalDataSource.getTasks() maybe be run before updateTasksFromRemoteDataSource() is done.
Code D
class DefaultTasksRepository(
private val tasksRemoteDataSource: TasksDataSource,
private val tasksLocalDataSource: TasksDataSource,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val myCoroutineScope: CoroutineScope
) : TasksRepository {
override suspend fun getTasks(forceUpdate: Boolean): Result<List<Task>> {
// Set app as busy while this function executes.
wrapEspressoIdlingResource {
if (forceUpdate) {
try {
updateTasksFromRemoteDataSource(myCoroutineScope)
} catch (ex: Exception) {
return Result.Error(ex)
}
}
return tasksLocalDataSource.getTasks()
}
}
private suspend fun updateTasksFromRemoteDataSource(myCoroutineScope: CoroutineScope) {
val remoteTasks = tasksRemoteDataSource.getTasks()
if (remoteTasks is Success) {
// Real apps might want to do a proper sync, deleting, modifying or adding each task.
tasksLocalDataSource.deleteAllTasks()
myCoroutineScope.launch {
remoteTasks.data.forEach { task ->
tasksLocalDataSource.saveTask(task)
}
}
} else if (remoteTasks is Result.Error) {
throw remoteTasks.exception
}
}
...
}
suspend functions look like regular functions from the call site's point of view because they execute sequentially just like regular synchronous functions.
What I mean by this is that the instructions following a plain call to a suspend function do not execute until the called function completes its execution.
This means that code A is fine (when forceUpdate is true, tasksLocalDataSource.getTasks() will never run before updateTasksFromRemoteDataSource() is done), and the coroutineScope in code B is unnecessary.
Now regarding code C, structured concurrency is here to save you.
People simply cannot call launch without a CoroutineScope receiver.
Since TaskRepository doesn't extend CoroutineScope, the code C as-is will not compile.
There are 2 ways to make this compile though:
Using GlobalScope.launch {}: this will cause the problem you expect, indeed. The body of such a launch will be run asynchronously and independently of the caller. updateTasksFromRemoteDataSource can in this case return before the launch's body is done. The only way to control this is to use .join() on the Job returned by the call to launch (which waits until it's done). This is why it is usually not recommended to use the GlobalScope, because it can "leak" coroutines.
wrapping calls to launch in a coroutineScope {...} inside updateTasksFromRemoteDataSource. This will ensure that all coroutines launched within the coroutineScope block are actually finished before the coroutineScope call completes. Note that everything that's inside the coroutineScope block may very well run concurrently, though, depending on how launch/async are used, but this is the whole point of using launch in the first place, isn't it?
Now with Code D, my answer for code C sort of still holds. Whether you pass a scope or use the GlobalScope, you're effectively creating coroutines with a bigger lifecycle than the suspending function that starts them.
Therefore, it does create the problem you fear.
But why would you pass a CoroutineScope if you don't want implementers to launch long lived coroutines in the provided scope?
Assuming you don't do that, it's unlikely that a developer would use the GlobalScope (or any scope) to do this. It's generally bad style to create long-lived coroutines from a suspending function. If your function is suspending, callers usually expect that when it completes, it has actually done its work.

Trigger event listeners async with Kotlin Coroutines

I have created an abstract Event class which is used to create events in Kotlin. Now I would like to use Coroutines to call each subscriber asynchronously.
abstract class Event<T> {
private var handlers = listOf<(T) -> Unit>()
infix fun on(handler: (T) -> Unit) {
handlers += handler
println(handlers.count())
}
fun emit(event: T) =
runBlocking {
handlers.forEach { subscriber ->
GlobalScope.launch {
subscriber(event)
}
}
}
}
And a concrete class that can be used to create event listeners and event publishers
class AsyncEventTest {
companion object : Event<AsyncEventTest>()
fun emit() = emit(this)
}
The issue is that when I run the following code I can see it creates all the listeners, but not even half of them are executed.
fun main(args: Array<String>) {
val random = Random(1000)
runBlocking {
// Create a 1000 event listeners with a random delay of 0 - 1000 ms
for (i in 1..1000)
AsyncEventTest on {
GlobalScope.launch {
delay(random.nextLong())
println(i)
}
}
}
println("================")
runBlocking {
// Trigger the event
AsyncEventTest().emit()
}
}
What am I missing here?
Update
When I remove delay(random.nextLong(), all handlers are executed. This is weird, since I'm trying to simulate different response times from the handlers that way and I think a handler should always execute or throw an exception.
You are running the event listeners with GlobalScope.launch() that does not interact with the surrounding runBlocking() scope. Means runBlocking() returns before all launched coroutines are finished. That is the reason you don't see the output.
BTW: your usage of coroutines and runBlocking is not recommended
You should add suspend to the emit() function. The same is true for the handler parameter - make it suspendable.