-
-
Save iosandroiddev/4077b7c67325b123f1996320c196c1be to your computer and use it in GitHub Desktop.
LifecycleObserver which allows easy cancelling of coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright 2018 Google LLC | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
class CoroutineLifecycleObserver : LifecycleObserver { | |
var job: Job = Job() | |
private set | |
@OnLifecycleEvent(Lifecycle.Event.ON_START) | |
fun start() { | |
// If the job is complete (happens after being previously stopped) | |
// lets create a new one | |
if (job.isCompleted) { | |
job = Job() | |
} | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) | |
fun cancel() { | |
// If the job is active (running) cancel it | |
if (job.isActive) { | |
job.cancel() | |
} | |
} | |
} | |
class DetailFragment : Fragment() { | |
private val coroutineLifecycle = CoroutineLifecycleObserver() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
// Add observer so any jobs are automatically cancelled | |
lifecycle.addObserver(coroutineLifecycle) | |
} | |
private fun runTask() { | |
// Set the coroutine parent from LifecycleObserver so that it will | |
// be automatically cancelled in onStop | |
launch(parent = coroutineLifecycle.job) { | |
// do something long-running | |
} | |
launch(parent = coroutineLifecycle.job) { | |
// do something else long-running | |
} | |
// both of these will be cancelled in onStop (if still running) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment