Giter VIP home page Giter VIP logo

kotlin-coroutines-android's Introduction

kotlin-coroutines-android

Useful extensions for coroutines.

Provide easier MainScope integration and auto disposable Job according to the view attached state.

AutoDisposable

Inspired by AutoDispose, auto cancel the job according to the attach state of corresponding view.

Usage

Add dependency in gradle:

api "com.bennyhuo.kotlin:coroutines-android-autodisposable:1.0"

Use asAutoDisposable to convert a Job to an AutoDisposableJob. Then the job will be cancelled when the view is removed.

In the sample below, delay(1000) will not be executed.

val anotherButton = Button(this)
parentView.addView(anotherButton, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)

anotherButton.setOnClickListener {
    GlobalScope.launch(Dispatchers.Main) {
        log(1)
        parentView.removeView(anotherButton)
        delay(1000)
        log(2)
    }.asAutoDisposable(it)
}

MainScope

Versions see ChangeLog.

Supplement for kotlinx.coroutines, providing useful extensions for android Views and easier way to integrate.

An instance of MainScope which use Dispatchers.Main as its dispatcher will be bound to the lifecycle of the corresponding Activity or Fragment. In other words, an instance of MainScope will be created when an activity is created and cancelled when the activity is destroyed or the view of the fragment is destroyed.

Usage

Add dependency in gradle:

api 'com.bennyhuo.kotlin:coroutines-android-mainscope:1.0'

Initialize this library in your customized Application:

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        MainScope.setUp(this)
    }
}

Implement BasicScoped to include View extensions for android sdk, RecyclerViewScoped for RecyclerView, DesignScoped for android support design library, AppCompatScoped for android support appcompat library. If more than one interfaces are used, just implement whatever you need.

class MainActivity : AppCompatActivity(), AppCompatScoped, RecyclerViewScoped {
    ...
}

To access the MainScope, just use the property mainScope. Be careful that it is not thread safe to use outsize the main thread.

class MainActivity : AppCompatActivity(), BasicScoped {
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        mainScope.launch {
            log("Hey!")
        }
        ...
    }
}

It is also easy to launch multi-coroutines with the withMainScope method:

...
withMainScope {
    launch {
        ...
    }

    async(Dispatchers.IO) {
        ...
    }
}
...

Most of the listeners borrowed from Anko are equipped with MainScope instead of the GlobalScope so that coroutines launched in these listeners will be cancelled when the corresponding activity is destroyed.

...
    button.onClick {
        log(1)
        delay(1000)
        log(2)
        textView.text = "Hello Coroutine!"
    }
...

onClick receives a suspend lambda as the body of the job. Once the button clicked, the lambda block will be started immediately on the main thread, and suspended at delay(1000). If you leave the activity by pressing the back key, the suspend lambda won't be dispatched since the job is cancelled by the MainScope installed in the activity.

About Fragment

Since android.app.Fragment is deprecated, we choose to support android.support.v4.app.Fragment only. If you include the library into the classpath, Fragment support will be automatically enabled for subtypes of FragmentActivity. Otherwise if you never use Fragment, don't worry, nothing will happen.

FragmentLifecycleCallbacks was added from v25.1.0 so older versions will not be supported.

Issue

Please feel free to issue and pull request.

License

MIT License

kotlin-coroutines-android's People

Contributors

bennyhuo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

kotlin-coroutines-android's Issues

Need more friendly information If not setUp in application

If not setUp in application, exception thrown as below when use the mainScope to create coroutine:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.bennyhuo.kotlin.android, PID: 6414
                  java.lang.AbstractMethodError: abstract method "kotlin.coroutines.CoroutineContext kotlin.coroutines.CoroutineContext.plus(kotlin.coroutines.CoroutineContext)"
                      at kotlinx.coroutines.CoroutineContextKt.newCoroutineContext(CoroutineContext.kt:57)
                      at com.bennyhuo.kotlin.coroutines.android.mainscope.job.BuildersKt.launch(Builders.kt:17)
                      at com.bennyhuo.kotlin.coroutines.android.mainscope.job.BuildersKt.launch$default(Builders.kt:14)
                      at com.bennyhuo.kotlin.coroutines.android.mainscope.BasicScoped$onClick$1.onClick(BasicScoped.kt:296)
                      at android.view.View.performClick(View.java:5204)
                      at android.view.View$PerformClick.run(View.java:21153)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.