Some helpful kotlin coroutines manager classes and extensions CoroutinesManager

Overview

Kotlin Coroutines Manager

Kotlin 1.6.0 Codacy Badge Awesome Kotlin Badge

Some helpful kotlin coroutines manager classes and extensions. You can turn every function into coroutine function with powerful try-catch-finally blocks

class MainActivity(
    private val coroutinesManager: ICoroutinesManager = CoroutinesManager()
) : AppCompatActivity(), ICoroutinesManager by coroutinesManager {

    // Async worker may be into your DI as uses case
    private val asyncWorker = AsyncWorker()
    
    fun tryCatch() = launchOnUITryCatch(tryBlock = {
        // do some work on ui
        val result = asyncWorker.awaitSomeHardWorkToComplete()
    }, catchBlock = {
        // catch every exception
    })
    
    // Sinse version 1.2.0
    private fun launchUiAsyncAction() = launchOnUITryCatchFinallyAsyncAwait(
        tryBlock = {

            delay(3000L)
            if (Random.nextInt(1, 20) % 2 == 0)
                throw RuntimeException("THERE IS AN ERROR")

            println("----> launchUiAsyncAction 'TRY' BLOCK COMPLETE")
        }, catchBlock = {
            println("----> ASYNC 'CATCH' BLOCK ${Thread.currentThread().name}")
            titleTextView.text = it.message
        }, finallyBlock = {

        })
    
    fun tryFinally() = launchOnUITryFinally(tryBlock = {
        // try some action that maybe produce an exceptions
    }, finallyBlock = {
        // do work when coroutine is done
    })
    
    fun tryCatchFinally() = launchOnUITryCatchFinally(tryBlock = {
        val resultForAwait = asyncWorker.createDeferrerForAwait()
        val finalResult: String = resultForAwait.await()    
    }, catchBlock = {
        // error here
    }, finallyBlock = {
        // final action here
    })
    
    fun doOnUiOnly() = launchOnUI { 
        // do some work on UI thread
    }   
}
    
class AsyncWorker(
    // You can store this class as global singleton into your DI framework
    private val asyncTaskManager: IAsyncTasksManager = AsyncTasksManager()
) : IAsyncTasksManager by asyncTaskManager {

    suspend fun awaitSomeHardWorkToComplete() = doTryCatchAsyncAwait(
        tryBlock = {
            println("----> ASYNC 'TRY' BLOCK")

            delay(3000L)
            if (Random.nextInt(1, 20) % 2 == 0)
                throw RuntimeException("THERE IS AN ERROR")

            "OPERATION COMPLETE"
        },
        catchBlock = {
            println("----> ASYNC 'CATCH' BLOCK")
            throw it
        }
    )
    
    suspend fun <T> createDeferrerForAwait(): Deferred<T> = doAsync {
        "SOME WORK HERE"
    }
}

You can use ICoroutinesManager as base implementation for your presenter in MVP or MVI architecture. Use IAsyncTasksManager as base implementation for hard work or async operations as UseCases and another tasks.

Build.gradle

allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

Gradle:

implementation 'com.github.Rasalexman:coroutinesmanager:x.y.z'

License

MIT License

Copyright (c) 2021 Alexandr Minkin ([email protected])

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You might also like...
Task Manager feat. real-time competitive system and user engagement
Task Manager feat. real-time competitive system and user engagement

Dira Что из себя представляет Dira? Android-приложение Directa (сокр. Dira) - это планер, который способен улучшить жизнь пользователей. Он позволяет

Some useful Android Kotlin utilities

Android-Kotlin-utilities Some useful Android Kotlin utilities Any PR are welcomed :) Please put your code in several files like this. it helps others

Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Clean Android multi-module offline-first scalable app in 2022. Including Jetpack Compose, MVI, Kotlin coroutines/Flow, Kotlin serialization, Hilt and Room.

Android Kotlin starter project - 2022 edition Android starter project, described precisely in this article. Purpose To show good practices using Kotli

Minecraft Package Manager

KSpigot Gradle Kotlin Template This is a template for creating a Paper Plugin with KSpigot, Gradle Kotlin DSL and the Kotlin programming language. How

This repo contains my solutions to some data structures and algorithms problems on leetcode.

DSA Playground This repository contains solutions to dsa problems in kotlin. NOTE: This file will get long, please consider using CtrlF DSA With Kun

Saga pattern implementation in Kotlin build in top of Kotlin's Coroutines.

Module Saga Website can be found here Add in build.gradle.kts repositories { mavenCentral() } dependencies { implementation("io.github.nomisr

Combine some useful exts in One place

Helper Extensions Extensions Combine some useful exts in One place Examples : this.errorMsg(msg = "Test error" , duration = 6000)

Releases(1.4.3)
  • 1.4.3(Nov 3, 2022)

  • 1.4.2(Jun 24, 2022)

  • 1.4.1(May 27, 2022)

  • 1.4.0(Feb 24, 2022)

  • 1.3.9(Nov 23, 2021)

  • 1.3.8(Nov 23, 2021)

    release version 1.3.8 with kotlin 1.6.0 coroutines-android 1.6.0-RC CoroutinesProvider now include jobs in lazy initialization remove all job.invokeOnCompletion { job.cancel() } callbacks

    Source code(tar.gz)
    Source code(zip)
  • 1.3.7(Oct 15, 2021)

    release version 1.3.7 with kotlin 1.5.31 coroutines-android 1.5.2 fix gradle.properties add java 11 support launchOnUI, launchOnUiAsyncBy, launchOnUiBy return a Job

    Source code(tar.gz)
    Source code(zip)
  • 1.3.6(Oct 15, 2021)

  • 1.3.4(Aug 15, 2021)

  • 1.3.2(May 11, 2021)

  • 1.3.1(May 11, 2021)

  • 1.3.0(May 11, 2021)

  • 1.2.35(Sep 17, 2020)

  • 1.2.33(Jun 27, 2020)

  • 1.2.31(Nov 25, 2019)

    Change function names in IAsyncTasksManager.kt:

    • doTryCatchWithAsync to doWithTryCatchAsync
    • doTryCatchFinallyWithAsync to doWithTryCatchFinallyAsync
    • doTryFinallyWithAsync to doWithTryFinallyAsync
    Source code(tar.gz)
    Source code(zip)
  • 1.2.30(Nov 25, 2019)

    New function with optional parameters: ICoroutinesManager.kt:

    • launchOnUiBy
    • launchOnUiAsyncBy

    IAsyncTasksManager.kt:

    • doAsyncAwaitBy
    • doWithAsyncAwaitBy
    Source code(tar.gz)
    Source code(zip)
  • 1.2.21(Nov 20, 2019)

    Added new functionality to IAsyncTasksManager.kt using withContext(asyncCoroutineContext):

    • doWithAsync
    • doTryCatchWithAsync
    • doTryCatchFinallyWithAsync
    • doTryFinallyWithAsync
    Source code(tar.gz)
    Source code(zip)
  • 1.2.1(Nov 7, 2019)

  • 1.2.0(Nov 7, 2019)

    Many refactoring and changes

    • ICoroutinesManager : IAsyncTasksManager and you can call any async methods inside launchOnUI Example:
    class MyCoroutinesWorker : ICoroutinesManager {
    
    fun onRepeateButtonClickListener() = launchOnUITryCatchFinally(
            tryBlock = {
    val result = doTryCatchAsyncAwait(
                    tryBlock = {
                        println("----> ASYNC 'TRY' BLOCK")
                        delay(3000L)
                       "OPERATION COMPLETE"
                    },
                    catchBlock = {
                        println("----> ASYNC 'CATCH' BLOCK")
                        throw it
                    }
                )
         }, catchBlock = {
            // Catch an Error on UI with it
        }, finallyBlock = {
          // final block
     })
    
    }
    
    • lazy initialization of Dispatcher in CoroutinesProvider.kt
    • default cancelationHandlersSet in CoroutinesProvider.kt and ICoroutinesManager can handle cancelation too
    • val ICoroutinesManager.isCancelled: Boolean and val ICoroutinesManager.isCompleted: Boolean
    • fun ICoroutinesManager.cancelAllCoroutines() - cancel all coroutines with async and UI jobs
    • replace var wasCancelled: Boolean from IAsyncTasksManager.kt by val IAsyncTasksManager.isCancelled: Boolean

    You can launch async task without calling launchOnUI with new functions:

    • launchOnUIAsyncAwait
    • launchOnUITryCatchAsyncAwait
    • launchOnUITryCatchFinallyAsyncAwait
    • launchOnUITryFinallyAsyncAwait Block try always will be called on Async Job

    Documentation added and example changed ❤️ Coroutines

    Source code(tar.gz)
    Source code(zip)
  • 1.1.3(Sep 10, 2019)

  • 1.1.2(Jul 18, 2019)

  • 1.1.1(Jul 18, 2019)

    Full API refactor. Major release version Changed function naming and added much more new functionality to IAsyncTaskManager.kt:

    • doTryCatchAsync
    • doTryCatchFinallyAsync
    • doTryFinallyAsync

    And await function that returns a response value from try... blocks Now finally block (CoroutineScope.(Throwable?) -> T) contains error as nullable parameter. If there is some error in coroutine it also passes into finally block too

    Source code(tar.gz)
    Source code(zip)
Owner
Alexandr Minkin
Lead Software Developer - Kotlin - Swift - Java - C#
Alexandr Minkin
Small kotlin library for persisting _single instances_ of kotlin data classes

PerSista Small library for persisting single instances of kotlin data classes. NB: PerSista uses typeOf() internally which is marked as @ExperimentalS

Eric Donovan 5 Nov 13, 2022
An AutoValue extension that generates binary and source compatible equivalent Kotlin data classes of AutoValue models.

AutoValue Kotlin auto-value-kotlin (AVK) is an AutoValue extension that generates binary-and-source-compatible, equivalent Kotlin data classes. This i

Slack 19 Aug 5, 2022
Clean MVVM with eliminating the usage of context from view models by introducing hilt for DI and sealed classes for displaying Errors in views using shared flows (one time event), and Stateflow for data

Clean ViewModel with Sealed Classes Following are the purposes of this repo Showing how you can remove the need of context in ViewModels. I. By using

Kashif Mehmood 22 Oct 26, 2022
Kotlin extensions, BindingAdapters, Composable functions for Android CameraX

Setup dependencies { implementation "com.github.skgmn:cameraxx:0.6.0" } Features CameraXX provides extensions methods for CameraX to use functions

null 12 Aug 9, 2022
Set of extensions for Kotlin that provides Discrete math functionalities

DiscreteMathToolkit Set of extensions for Kotlin that provides Discrete Math functionalities as an Kotlin extension functions. To stay current with ne

Marcin Moskała 177 Dec 15, 2022
Flowbius provides interoperability extensions for using Kotlin Flows with Mobius

Flowbius Flowbius provides interoperability extensions for using Kotlin Flows with Mobius. They allow conversion from Flows to Mobius types and vice v

Atlassian Labs 54 Jul 19, 2022
Various Ktor extensions and plugins.

Ktor Plugins Collection of useful Ktor plugins. All plugins are hosted on Maven central and have same version that should be similar to the latest ver

Lukas Forst 25 Nov 24, 2022
DS-for-Kotlin - Some classic data sturctures write in kotlin for fun

DS-for-Kotlin Just write some classic data structure by kotlin during my leisure

ccyyxx 2 Jan 30, 2022
A simple ToDo Task Manager App made in Kotlin using Room DataBase.

ToDo List App ?? About A simple To-Do List Management App that helps you get things done. Built with Kotlin, it helps the user to add their task. User

Tanya Gupta 17 Dec 12, 2022
Kotlin Example of how to organize your code using MVC and some patterns seen in class

Kotlin Example of how to organize your code using MVC and some patterns seen in class

José Luis González Sánchez 3 Mar 23, 2022