AndroidCoroutineScopes

Additional

Language
Kotlin
Version
N/A
Created
Sep 16, 2018
Updated
Nov 10, 2018
Owner
Adriel Café (adrielcafe)
Contributor
Adriel Café (adrielcafe)
1
Activity
Badge
Generate
Download
Source code
APK file

Blurb

AndroidCoroutineScopes

Starting from 0.26.0 release we should define a scope for new coroutines (docs).

To avoid this boilerplate code I've created this small library that implements the most common CoroutineScopes used in Android apps.

How to use

Just extend your Activity/Fragment/ViewModel with the corresponding implementation.

// AppCompat scopes
class MyActivity : CoroutineScopedActivity()

class MyFragment : CoroutineScopedFragment()

class MyDialogFragment : CoroutineScopedDialogFragment()

// ViewModel scopes
class MyViewModel : CoroutineScopedViewModel()

class MyAndroidViewModel(app: Application) : CoroutineScopedAndroidViewModel(app)

Example

class MainActivity : CoroutineScopedActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Don't use launch(UI), it's deprecated now
        launch {
            Log.d(TAG, "MAIN THREAD")
            withContext(Dispatchers.Default){
                Log.d(TAG, "OTHER THREAD")
            }
        }
    }

}

Import to your project

// Add JitPack to your repositories if needed
repositories {
 maven { url 'https://jitpack.io' }
}

// AppCompat scopes
implementation 'com.github.adrielcafe.androidcoroutinescopes:appcompat:1.0.1'

// ViewModel scopes
implementation 'com.github.adrielcafe.androidcoroutinescopes:viewmodel:1.0.1'