Created
October 26, 2018 07:59
-
-
Save mayojava/103d5c146ab7608d400055241f052c40 to your computer and use it in GitHub Desktop.
Corotuine Observer
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
class CoroutineObserver: LifecycleObserver, CoroutineScope { | |
private lateinit var job: Job | |
override val coroutineContext: CoroutineContext | |
get() = job + Dispatchers.Default | |
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) | |
fun onCreate() { | |
job = Job() | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) | |
fun onDestroy() { | |
job.cancel() | |
} | |
} | |
class TestActivity: AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
lifecycle.addObserver(CoroutineObserver()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment