Skip to content

An unofficial Kotlin wrapper of Twitter4J with coroutines

License

Notifications You must be signed in to change notification settings

417-72KI/Twitter4Kt

Repository files navigation

Twitter4Kt

publish Maven Central

Twitter4Kt is a wrapper for Twitter4J to support Kotlin Coroutines.

Motivation

All of the functions in Twitter4J are synchronous, and it may cause crash on GUI(Especially Android) apps.
Twitter4Kt wraps some of Twitter4J functions with suspend and use Dispatchers.IO to execute Twitter's apis.

If using Twitter4Kt instead of Twitter4J directly, you needs no more calling Twitter's apis with withContext in coroutines.

Before

scope.launch {
    prepare()
    withContext(Dispatchers.IO) {
        try {
            twitter.v1.tweets().updateStatus(text)
            withContext(Dispatchers.Main) {
                onSuccess()
            }
        } catch (e: TwitterException) {
            withContext(Dispatchers.Main) {
                onError()
            }
        } finally {
            withContext(Dispatchers.Main) {
                onFinally()
            }
        }
    }
}

After

scope.launch {
    prepare()
    try {
        twitter.v1.tweets().updateStatus(text)
        onSuccess()
    } catch (e: TwitterException) {
        onError()
    } finally {
        onFinally()
    }
}

Installation

Gradle(Groovy)

repositories {
    mavenCentral()
}

dependencies {
    implementation 'io.github.417-72ki:twitter4kt:1.0.0'
}

Gradle(Kotlin)

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.github.417-72ki:twitter4kt:1.0.0")
}

Usage example

val twitter = Twitter.Builder()
    .setOAuthConsumer("consumer key", "consumer secret")
    .setOAuthAccessToken("access token", "access token secret")
    .build()
scope.launch {
    twitter.v1.tweets().updateStatus("Hello world!")
}

License

Apache License Version 2.0

Author

417-72KI