Transform java callback to kotlin suspend method.

Overview

Callback2Coroutines

Transform Java callback to coroutines suspend method.
将传统Java callback 方法转换为kotlin中的suspend方法。

接入指南

根目录下加入jatpack的repository:

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

在app的build.gradle中加入依赖,release_version为最新release版本。

    implementation 'com.github.RainFool.Callback2Coroutines:coroutines_annotation:release_version'
    kapt 'com.github.RainFool.Callback2Coroutines:coroutines_processor:release_version'

需要先使用CallbackTransformer注解标记一个转换器,作用是将协程和callback连接,比如:

/**
 * 默认的转换器
 * @author rainfool
 */
object CoroutinesTransformer {
    @CallbackTransformer
    fun <T> defaultTransformer(it: Continuation<CoroutineResult<T>>): IResultListener<T> {
        return object : IResultListener<T> {
            override fun onSuccess(result: T) {
                it.resume(CoroutineResult(true, result))
            }

            override fun onError(errorCode: Int, errorMessage: String?) {
                it.resume(CoroutineResult<T>(false, null, errorCode, ""))
            }

        }
    }
}

最后,在含有callback的方法上标记@CoroutineMethod即可,编译完模块后会自动生成含有协程方法的类。

原理简述

在维护老项目时,经常遇到使用callback进行回调,比如下列代码,在MyClass中声明了一个静态方法和一个普通方法:

// 静态方法
public static void testFunc1(ICallback<String> callback) {}

// 普通方法
public void testFunc2(ICallback<Param> callback) {}

而多重的嵌套会让代码十分不友好。

本项目可以通过一个简单的注解@CoroutineMethod将上述两种,callback在最后一个参数的Java代码转换为kotlin的suspend方法:

// 生成的协程代码
object MyClassCoroutine {
  suspend fun testStaticFunc(p1: List<Int>, p2: List<Param>): CoroutineResult<Param> =
      suspendCoroutine<CoroutineResult<Param>> {
    val callback = callbackTransformer(it)
    testStaticFunc(p1, p2, callback)
  }

  suspend fun testFunc1(): CoroutineResult<String> = suspendCoroutine<CoroutineResult<String>> {
    val callback = callbackTransformer(it)
    testFunc1(callback)
  }
}

suspend fun MyClass.testFunc2(): CoroutineResult<Param> = suspendCoroutine<CoroutineResult<Param>> {
  val callback = callbackTransformer(it)
  this.testFunc2(callback)
}

其中,静态方法将会生成一个新类,已原始类名+Coroutine命名,普通方法将生成一个kotlin扩展方法。

随后就可以愉快的进行subspend方法调用了:

    val data = async { MyClassCoroutine.testFunc1() }
    
    val data = MyClass.testFunc2()
You might also like...
Greatly simplifies the complexities of Kotlin's reflection of Java

CatReflect 这是一个可以极大简化 Java 反射的复杂操作的工具,适用于 Kotlin & Java This is a tool that grea

Unofficial Actions on Google SDK for Kotlin and Java
Unofficial Actions on Google SDK for Kotlin and Java

Actions On Google Client Library This is a port of the official Node.js SDK to Kotlin. This can also be used from Java and any JVM language. Quick Fac

Theia - A Kotlin program used to analyze and discover backdoors in Minecraft Java 1.12.2 forge mods

Theia A Kotlin program used to analyse and discover backdoors in Minecraft Java

A tool that can mock out an existing Appium session, supports both Java and Kotlin.

appium-mocker A tool that can mock out an existing Appium session, supports both Java and Kotlin. How to install latest appium-mocker Beta/Snapshots

A Java Virtual Machine written in Kotlin
A Java Virtual Machine written in Kotlin

jvm.kotlin A Java Virtual Machine written in Kotlin. Introduction jvm.kotlin is a toy JVM programmed in Kotlin. The main purpose of this project is le

Java REPL on Android with BeanShell
Java REPL on Android with BeanShell

BeeShell Java REPL on Android with BeanShell. Useful for quickly checking some framework API behavior, or calling Java APIs with the permissions of AD

This repository is part of a Uni-Project to write a complete Compiler for a subset of Java.

Compiler This repository is part of a Uni-Project to write a complete Compiler for a subset of Java. Features error recovery using context sensitive a

Write a Ghidra Extension without using Java or Eclipse!

Ghidra Extension in Kotlin using IntelliJ IDEA Write a Ghidra Extension without using Java or Eclipse! Setup Hit Use this template at the top of the r

A library for building Java only Zygisk/Riru modules.

A library for building Java only Zygisk/Riru modules.

Releases(0.0.2)
Owner
RainFool
Reading the source code.
RainFool
A property/method accessor library for the JVM, written in Kotlin

unlok - unlock your JVM a property/method accessor library for the JVM, written in Kotlin. how to import you can import unlok from maven central just

xtrm 2 Oct 27, 2022
Android Spinner Dialog Library supported on both Java and Kotlin, Use for single or multi selection of choice

SpinnerDialog Android Spinner Dialog Library, Use for single or multi selection of choice Android UI Download To include SpinnerDialog in your project

Hamza Khan 55 Sep 15, 2022
Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.

Codename One - Cross Platform Native Apps with Java or Kotlin Codename One is a mobile first cross platform environment for Java and Kotlin developers

Codename One 1.4k Jan 9, 2023
StaticLog - super lightweight static logging for Kotlin, Java and Android

StaticLog StaticLog is a super lightweight logging library implemented in pure Kotlin (https://kotlinlang.org). It is designed to be used in Kotlin, J

Julian Pfeifer 28 Oct 3, 2022
Auto-generate the fastest possible Parcelable implementations for Java and Kotlin

This project is deprecated It will still be maintained, but no new features will be added. Please use Parcelize, as it is the official way of generati

Bradley Campbell 492 Nov 17, 2022
From Java to Kotlin Cheat Sheet

From Java to Kotlin Cheat Sheet Page: http://fabiomsr.github.io/from-java-to-kotlin/ Programmatically inspired from swift-is-like-go and visually insp

Fabio Santana 552 Dec 23, 2022
A Kotlin compiler plugin that allows Java callers to pass in null for default parameters

kotlin-null-defaults (Compiler plugin) (Gradle Plugin) ( Currently pending approval) A Kotlin compiler plugin that allows Java callers to pass in null

Youssef Shoaib 7 Oct 14, 2022
🔨 Template for easy hosting of your Java/Kotlin libraries on GitHub

?? kotlin-jvm-library-template Another template for easy hosting your Java/Kotlin libraries on GitHub. Features boilerplate for Kotlin/Java projects w

Viktor 0 Jan 7, 2022
Kotlin and Java API for generating .swift source files.

SwiftPoet SwiftPoet is a Kotlin and Java API for generating .swift source files. Source file generation can be useful when doing things such as annota

Outfox 232 Jan 2, 2023
Sample Code for fake Kotlin library written in Java

Jatlin このリポジトリは ブログ記事 のためのサンプルコードです。詳細は記事をご覧ください。 プロジェクト構成 :java-lib にKotlinに偽装したJavaファイルが含まれます。 :kotlin-lib は :java-lib をビルドしたJARファイルをKotlinから読み込んで実行

Takaki Hoshikawa 3 Dec 10, 2021