在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):steelkiwi/Getting-started-with-Kotlin开源软件地址(OpenSource Url):https://github.com/steelkiwi/Getting-started-with-Kotlin开源编程语言(OpenSource Language):Kotlin 94.8%开源软件介绍(OpenSource Introduction):Getting started with Kotlin And third-party libraries Glide, Dagger 2, Retrofit 2, Realm, RxJava and MVP architecture on AndroidhereRead our new articleIt’s not a mystery to Android developers all over the world that the whole IT community has been trying to find a decent replacement for Java. Until 2011, before the Kotlin creation had been announced, Scala was the most suitable candidate. However, when JetBrains presented Kotlin programming language and its source code, it gradually became the strongest Java alternative in the field. This resulted in Kotlin becoming the official Android development language in 2017. Kotlin was claimed to be a response to the massive amounts of code developers often had to write in Java and to Scala’s low-speed compilation. Today, many famous IT companies use Kotlin in their projects. The attention to this language is continuing to grow, as it wins over developers with its syntax and the fact that Kotlin is supported by several IDEs as a plugin. Even Jake Wharton, a recognized Android gospeller, uses Kotlin in his own projects, thus encouraging the whole Android community to use this language. Let’s stay in tune with this trend and try Kotlin in practice to see its extensively debated pros and cons. Also, we will learn how to start developing Android applications in Kotlin. What does Kotlin hide?Mostly Kotlin is commended for its briefness and code safety and also for compatibility with Java and flexible usage. It’s hard to list all its advantages, so let’s consider the most interesting ones.Strong sides of Kotlin:
As for today, Kotlin isn’t very popular. The language is young and the community is yet to be formed. However, the ambitions for Kotlin are high. It has been under development for more than five years and the developers tried their best to avoid Java’s past mistakes. Java’s principle “Write Once Run Anywhere” doesn’t apply here as the language constantly changes and improves. Kotlin developers promise many interesting features, including the coverage of current Scala functionality. With so many advantages, Kotlin almost seems to be the perfect programming language. However, it does also have some cons, even though they might not be as obvious. WEAKNESSES OF KOTLIN:
Let’s dwell on compatibility and look closely at the example of a simple application development using such popular libraries like:
The app serves as a good instance of libraries data usage and implementation of MVP architecture:Let’s proceed to the developmentIt’s pretty easy to start the development process with Kotlin. First of all, you need to install the plugin:After that configure your project. The easiest way to do this is to press Ctrl+Shift+A and find Configure Kotlin in Project item that will appear in autocomplete:To convert existing Java classes to Kotlin you need to find the command named Convert Java to Kotlin:Now let's start the integration of the needed librariesNow let's start the integration of the needed libraries A few words before we start. Some libraries like Dagger 2 require Annotation Processing. Java Annotation Processing is not suitable for Kotlin. That’s why it includes its own Annotation Processing Tool for Kotlin (kapt), here is a great opinion on it.build.gradle file:To activate it you need to add this in thekapt {
generateStubs = true
}
buildscript {
ext.supportVersion = '25.0.0'
ext.daggerVersion = '2.7'
ext.retrofitVersion = '2.1.0'
ext.rxVersion = '1.2.1'
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath "io.realm:realm-gradle-plugin:2.1.1"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.0'
testCompile 'junit:junit:4.12'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "com.android.support:cardview-v7:${supportVersion}"
compile "com.android.support:design:${supportVersion}"
// Dagger 2
compile "com.google.dagger:dagger:${daggerVersion}"
kapt "com.google.dagger:dagger-compiler:${daggerVersion}"
provided "org.glassfish:javax.annotation:3.1.1"
//Retrofit 2
compile "com.squareup.retrofit2:retrofit:${retrofitVersion}"
compile "com.squareup.retrofit2:adapter-rxjava:${retrofitVersion}"
compile "com.squareup.retrofit2:converter-gson:${retrofitVersion}"
compile 'com.google.code.gson:gson:2.8.0'
compile "io.reactivex:rxjava:${rxVersion}"
compile "io.reactivex:rxandroid:${rxVersion}"
compile 'com.github.bumptech.glide:glide:3.7.0'
} inheriting class from Application and configure Realm and dependencies graph for Dagger 2 developed by Google:Then we createclass AppDelegate : Application() {
var injector: AppInjector? = null
@Singleton
@Component(modules = arrayOf(NewsModule::class))
interface AppInjector {
fun inject(activity: MainActivity)
}
override fun onCreate() {
super.onCreate()
injector = DaggerAppDelegate_AppInjector.builder().build()
Realm.init(this)
val config = RealmConfiguration.Builder().build()
Realm.setDefaultConfiguration(config)
}
} interface with one method that will receive news feed:To work with HTTP we use Retrofit. We need to create aninterface NewsApiInterface {
@GET("/feeds/newsdefaultfeeds.cms?feedtype=sjson")
fun getNews(): Observable<NewsResponse>
} NewsModule class wherein the injected objectives will be created:We create@Module
class NewsModule {
@Provides
@Singleton
fun provideNewsPresenter(): NewsPresenter {
return NewsPresenter()
}
@Provides
@Singleton
internal fun provideNewApiInterface(): NewsApiInterface {
val retrofit = Retrofit.Builder()
.baseUrl(Constants.NEWS_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
return retrofit.create(NewsApiInterface::class.java)
}
} NewsPresenter class we will use RxAndroid and Realm for news feed processing and caching :Insubscription = mNewsApiInterface!!
.getNews()
.map { it.newsItem }
.flatMap({ items ->
Realm.getDefaultInstance().executeTransaction({ realm ->
realm.delete(NewsItem::class.java)
realm.insert(items)
})
Observable.just(items)
})
.onErrorResumeNext { throwable ->
val realm = Realm.getDefaultInstance()
val items = realm.where(NewsItem::class.java).findAll()
Observable.just(realm.copyFromRealm(items))
}
.observeOn(AndroidSchedulers.mainThread())
.doOnTerminate { mNewsView?.hideLoading() }
.subscribe({ mNewsView?.onNewsItemLoaded(it) }, { mNewsView?.onError(it) }) Projects source code is available on this Repository =) Let’s sum upAll in all, Kotlin is a modern and secure programming language that simplifies Android apps development. It looks like a distinct alternative to Java as it has good documentation and it is simple enough for understanding. We hope that this article helped you to figure out how to create a project on Kotlin and integrate the needed libraries. License
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论