Kotlin Dagger2 cannot find symbol ApplicationModule_ProvideApplicationFactory - android

I'm trying to use Dagger2 with Kotlin but today trying to compile got this error:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Error:(5, 43) error: cannot find symbol class ApplicationModule_ProvideApplicationFactory
(App) Build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.ilyarb.geotags"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
dexOptions {
javaMaxHeapSize "2048M"
}
}
kapt {
generateStubs = true
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
final SUPPORT_LIBRARY_VERSION = "23.3.0"
final PLAY_SERVICES_VERSION = "8.4.0"
compile "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
// Dagger 2
compile 'com.google.dagger:dagger:2.0.2'
kapt 'com.google.dagger:dagger-compiler:2.0.2'
provided 'org.glassfish:javax.annotation:10.0-b28'
compile "com.google.android.gms:play-services-maps:$PLAY_SERVICES_VERSION"
compile "com.google.android.gms:play-services-location:$PLAY_SERVICES_VERSION"
compile 'com.jakewharton.timber:timber:4.1.0'
compile 'com.jakewharton.byteunits:byteunits:0.9.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
testCompile 'junit:junit:4.12'
}
repositories {
mavenCentral()
}
buildscript {
ext.kotlin_version = '1.0.1-2'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
root build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Application class
package com.ilyarb.geotags
import android.app.Application
import com.google.android.gms.common.api.GoogleApiClient
import com.ilyarb.geotags.injection.component.ApplicationComponent
import com.ilyarb.geotags.injection.component.DaggerApplicationComponent
import com.ilyarb.geotags.injection.module.ApplicationModule
import com.squareup.leakcanary.LeakCanary
import timber.log.Timber
import javax.inject.Inject
class GeotagApp : Application() {
#Inject lateinit var mGoogleApiClient: GoogleApiClient
companion object {
#JvmStatic lateinit var mApplicationComponent: ApplicationComponent
}
override fun onCreate() {
super.onCreate()
LeakCanary.install(this)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
mApplicationComponent = DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(this))
.build()
mApplicationComponent.inject(this)
}
}
Application Component
package com.ilyarb.geotags.injection.component
import android.app.Application
import com.ilyarb.geotags.injection.module.ApplicationModule
import dagger.Component
import javax.inject.Singleton
#Singleton
#Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun inject(application: Application)
}
Application Module
package com.ilyarb.geotags.injection.module
import android.app.Application
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationServices
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
#Module
class ApplicationModule(private val mApplication: Application) {
#Provides
#Singleton
fun provideGoogleApiClient() : GoogleApiClient {
return GoogleApiClient.Builder(mApplication)
.addApi(LocationServices.API)
.build()
}
}
It generates DaggerApplicationComponent but when i try to run application it fails with this error.
I've already tried to clean and rebuild the project but it didn't work.
Any help will be greatly appreciated.

Looking through your project I noticed some of your dagger Modules have providing methods with similar names like providesContext(). Dagger 2 (or kapt) may have a problem with it, which results in your error. Please try renaming them, so that all #Provides methods have unique names.
Also annotations have the runtime retention in Kotlin by default, so you don't need to use #Retention(AnnotationRetention.RUNTIME).

Related

implementing hilt in android with kapt Execution failed for task ':app:kaptDebugKotlin'

I have been using hilt in my several android projects. But since I have updated my android studio to latest version Chipmunk// 2021.2.1, this error comes every time when I just build project
Execution failed for task ':app:kaptDebugKotlin'.
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
java.lang.reflect.InvocationTargetException (no error message)
I am checking it on sample app which is just just one dependency injection, using hilt and kapt.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
allprojects {
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
dependencies {
// Hilt Classpath for Java
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.38.1'
}
}
plugins {
id 'com.android.application' version '7.2.1' apply false
id 'com.android.library' version '7.2.1' apply false
id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
apply plugin: 'com.android.application'
apply plugin: 'org.jetbrains.kotlin.android'
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
android {
compileSdk 32
defaultConfig {
applicationId "com.example.hiltkotlinpractice"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation("com.google.dagger:hilt-android:2.38.1")
kapt("com.google.dagger:hilt-android-compiler:2.38.1")
kapt 'androidx.hilt:hilt-compiler:1.0.0'
}
#HiltAndroidApp
class App: Application()
#Module
#InstallIn(ActivityComponent::class)
class AppModule {
#Provides
fun provideInterface(): APIProvider {
return APIProvider()
}
}
class Repo #Inject constructor(
val apiProvider: APIProvider
) {
fun get() = apiProvider.getData()
}
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val repo = Repo(APIProvider())
Log.d(TAG, repo.get())
}
}
Try using "annotationProcessor" instead of the "kapt" in the build.gradle dependencies. Worked for me.

Test cases are not running with hilt | custom testInstrumentationRunner is not working.....?

Project
buildscript {
ext {
kotlin_version = "1.5.31"
hilt_version = "2.38.1"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
(:app)
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.priyanshumaurya8868.hilttesting"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "com.priyanshumaurya8868.hilttesting.HiltTestRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
androidTestImplementation "com.google.truth:truth:1.1.3"
}
Inside (andorid test)
TestRunner
package com.priyanshumaurya8868.hilttesting
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
class HiltTestRunner: AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, HiltTestRunner::class.java.name, context)
}
}
Module
package com.priyanshumaurya8868.hilttesting
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
#Module
#InstallIn(SingletonComponent::class)
object TestAppModule {
#Provides
fun provideRandomString()="random testing 1"
}
unitTest
package com.priyanshumaurya8868.hilttesting
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
#SmallTest
#HiltAndroidTest
class TestString {
#get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)
#Before
fun init(){
hiltRule.inject()
}
#Inject
lateinit var str :String
#Test
fun test_empty_string(){
assertThat(str).isNotEmpty()
}
}
TestResult
test Result (0/0)
*10/05 16:13:47: Launching 'TestString' on HMD Global Nokia 6.1 Plus.
App restart successful without re-installing the following APK(s): com.priyanshumaurya8868.hilttesting
Running tests
$ adb shell am instrument -w -m -e debug false -e class 'com.priyanshumaurya8868.hilttesting.TestString' com.priyanshumaurya8868.hilttesting.test/com.priyanshumaurya8868.hilttesting.HiltTestRunner
Connected to process 26841 on device 'hmd_global-nokia_6_1_plus-DRGID19032402270'.**

Starting out with Room, encountered this error: incompatible types: NonExistentClass cannot be converted to Annotation

I have looked at the solutions presented at each of these links.
NonExistentClass cannot be converted to Annotation - app:kaptDebugAndroidTestKotlin
-- Not relevant as I am not using JUnit5.
error: incompatible types: NonExistentClass cannot be converted to Annotation #error.NonExistentClass()
-- Two issues, one is I don't know where to put kapt { } and I tried leaving it as a global, but that didn't do anything and putting it in dependency caused a error.
NonExistentClass cannot be converted to Annotation
-- Unsure where to set generateStubs to true and where to set correctErrorTypes to true in my build.gradle file. I don't know if I can use annotationProcessor on it's own.
On my own I tried to implement android.arch before realizing it is deprecated.
I tried to use ksp but that returned an error stating that the complier doesn't know where the ksp() method is. Using
implementation("com.google.devtools.ksp:symbol-processing-api:1.5.0-1.0.0-alpha10")
did not resolve the error with ksp.
The error message exactly: "error: incompatible types: NonExistentClass cannot be converted to Annotation"
#error.NonExistentClass()
Here is my module build.gradle
plugins {
id 'com.android.application'
// id 'com.android.feature'
id 'kotlin-android'
id 'kotlin-kapt'
//id 'dagger.hilt.android.plugin'
//id 'kotlin-ksp'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android'
//apply plugin: 'dagger.hilt.android.plugin'
//apply plugin: 'com.android.feature'
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.testingdatabases"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
kapt {
correctErrorTypes = true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
// ROOM - -- - --- - - - >
def room_version = "2.3.0"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor "androidx.room:room-compiler:$room_version"
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$room_version")
// To use Kotlin Symbolic Processing (KSP)
// ksp("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$room_version")
api("io.grpc:grpc-kotlin-stub:1.0.0")
// implementation("com.google.devtools.ksp:symbol-processing-api:1.5.0-1.0.0-alpha10")
// < -- - - - End of Room stuff
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Here is the project's build.gradle file,
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
def nav_version = "2.3.0-alpha01"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Here is the applications code,
package com.example.testingdatabases
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.room.RoomDatabase;
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
#Entity
data class User(
#PrimaryKey val uid: Int,
#ColumnInfo(name = "first_name") val firstName: String?,
#ColumnInfo(name = "last_name") val lastName: String?
)
#Dao
interface UserDao {
#Query("SELECT * FROM user")
fun getAll(): List<User>
#Query("SELECT * FROM user WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List<User>
#Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
#Insert
fun insertAll(vararg users: User)
#Delete
fun delete(user: User)
}
#Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
in gradle implementation "a-b-x" is used and in kotlin dsl implemntation("a-b-x") is used ,don't mix
Your database is not build properly (According to me) Here

Build failed after adding Hilt components in Android project

I was trying to explore Hilt with simplest possible example, but my application isn't building. I added all the dependencies but when I try to build, it shows an error indicating not finding the hilt gradle plugin.
Here are my codes:
build.gradle(project)
ext.kotlin_version = "1.5.20"
ext.hilt_version = '2.35'
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle(app)
plugins{
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.bonny.tutorial.hilttest"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.5.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
//hilt
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
Application Class (included in the Manifest too)
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
#HiltAndroidApp
class TextApplication : Application() {
}
Dependency class (MyTexts.kt)
class MyTexts #Inject constructor(){
val text = "Hello World"
}
MainActivity.kt
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var tv: TextView
#Inject lateinit var myTexts: MyTexts
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tv = findViewById(R.id.myText)
tv.text = myTexts.text
}
}
and the error looks like this:
public final class MainActivity extends androidx.appcompat.app.AppCompatActivity {
^
Expected #AndroidEntryPoint to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
See https://dagger.dev/hilt/gradle-setup.html
[Hilt] Processing did not complete. See error above for details.
Please suggest.
Kotlin 1.5.20 just came out (24 jun 2021) so there seems to be some compatibility issue. You can bring down to ext.kotlin_version = "1.5.10" in your build.gradle(project)
Also, Update hilt to latest 2.37
project build
classpath "com.google.dagger:hilt-android-gradle-plugin:2.37"
app build:
//Dagger - Hilt
implementation "com.google.dagger:hilt-android:2.37"
kapt "com.google.dagger:hilt-android-compiler:2.37"

Unresolved reference: launch. I can't write example with kotlin coroutines

I am going to learn kotlin coroutines, but i got problem on android studio.
I did need imports of library in gradle, but I got problems with code compiler.
I just can't use launch. Kotlin version is 1.3.50. Error: Unresolved Reference Launch
Import
import kotlinx.coroutines.delay
import kotlinx.coroutines.*
Code which I try to use:
suspend fun firstCoroutine(){
println("Kotlin Start")
launch(CommonPool){
delay(2000)
println("Kotlin Inside")
}
println("Kotlin End")
}
My build.gradle app file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
//эти файлы используюстя для компиляции, построения и упаковки приложений и библиотек
//настройки для модуля
android {
compileSdkVersion 28
defaultConfig {
applicationId "guard_studio.akira.firstcotlinproject"//идентификатор приложения
minSdkVersion 17//минимальная поддерживаемая версия сдк
targetSdkVersion 28
versionCode 1
versionName "1.0"//версия приложения для гугл плэй
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
//список библиотек подключенных к проекту
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2"
}
build.gradle level project
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url "http://dl.bintray.com/kotlin/kotlin-eap"
}
}
}
Although it is the wrong natural language (Russian) - Please translate your post to English so other people can understand you - I would define your problem like this:
'Can't start a coroutine inside my suspend function'
Answer to that question:
New coroutines can only be started inside a scope.
Suspend function don't provide this scope. Their feature: they can be called within a coroutine. Please read this introduction into coroutines for more info.
Easiest solution:
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
fun firstCoroutine(){
println("Kotlin Start")
GlobalScope.launch(){
delay(2000)
println("Kotlin Inside")
}
println("Kotlin End")
}
Your could also define a runBlocking:
import kotlinx.coroutines.runBlocking
fun firstCoroutine() = runBlocking {
println("Kotlin Start")
launch(){
delay(2000)
println("Kotlin Inside")
}
println("Kotlin End")
}
It seems that you are following an outdated tutorial. You have to use CoroutineScope if you want to use latest version of the coroutines. Just for start you can use GlobalScope:
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
suspend fun firstCoroutine() {
println("Kotlin Start")
GlobalScope.launch {
delay(2000)
println("Kotlin Inside")
}
println("Kotlin End")
}

Categories

Resources