Skip to content

fengzhizi715/Kotlin-Coroutines-Utils

Repository files navigation

Kotlin-Coroutines-Utils

@Tony沈哲 on weibo License

介绍

该库封装了 Kotlin Coroutines 常用的工具类,为本人在日常开发实践中的积累,持续更新ing

该库为本人以下几个库提供底层的依赖:

下载安装

将它添加到项目的 root build.gradle 中:

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

然后在项目或者在 module 中添加:

Gradle:

implementation 'com.github.fengzhizi715.Kotlin-Coroutines-Utils:common:v1.1.8'

Feature

1. SafeCoroutineScope

SafeCoroutineScope 的 CoroutineContext 使用了 SupervisorJob 和 CoroutineExceptionHandler,因此是安全的 CoroutineScope。

基于 SafeCoroutineScope 封装,提供了以下函数:

  • runOnUI() : 运行在主线程,支持异常处理、无返回结果
  • runInBackground(): 运行在后台线程,支持异常处理、无返回结果
  • asyncOnUI(): 运行在主线程,支持异常处理、有返回结果
  • asyncInBackground(): 运行在后台线程,支持异常处理、有返回结果
  • withUI(): 使用 Dispatchers.Main 切换线程
  • withIO(): 使用 Dispatchers.IO 切换线程
  • withDefault(): 使用 Dispatchers.Default 切换线程
  • withUnconfined(): 使用 Dispatchers.Unconfined 切换线程

2. Extension

为 Job、Deferred、Flow 提供一系列的扩展函数

2.1 Job

  • safeCancel(): 安全地取消 job
  • then()

2.2 Deferred

  • then()
  • thenAsync()
  • awaitOrNull(): Deferred 返回的值以及对超时的处理,超时会返回 null
  • map()
  • flatMap()
  • concatMap()
  • zipWith()

2.3 Flow

  • toSuspend()
  • onCompleted()
  • awaitFirst()
  • resumeOnError()

联系方式

Wechat:fengzhizi715

Java与Android技术栈:每周更新推送原创技术文章,欢迎扫描下方的公众号二维码并关注,期待与您的共同成长和进步。

License

Copyright (C) 2018 - present, Tony Shen.

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.