https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
j

Joey

12/11/2019, 5:10 AM
Hi guys, i have this function inside my kotlin shared library.
Copy code
suspend fun fetchUsers(): List<String> {
        val response = client.get<JsonObject> { url("$baseUrl/heartbeat.json") }
        val userIds = response.keys.toList()
        return userIds
    }
Now im trying to implement it in a pure old java project. I enabled the kotlin plugin in this project and created this function:
Copy code
fun fetchUsersFromKtLib(): List<String> {
    val api = HeartbeatApi()
    val users = GlobalScope.future { api.fetchUsers()  }
    return users.get()
}
Now everytime im calling this
fetchUsersFromKtLib
function, there is a jank in my UI (a freeze). Im trying to solve this problem for about 3 days now. So far this is the cleanest way i called the function from the kotlin shared library. What can you suggest to avoid any UI freeze? Thanks guys!
Im starting to think of removing the fetching of data in my kotlin library. I will just create a function that returns the api endpoint and do the fetching in java. Which is the better approach?
y

yshrsmz

12/11/2019, 5:32 AM
it's because your second function is synchronous
Copy code
fun fetchUsersFromKtLib(callback: (users:List<String>) -> Unit) {
    val api = HeartbeatApi()
    GlobalScope.launch { 
        val users = api.fetchUsers()
        callback(users)
    }
}
you need to convert to callback or return as CompletableFuture and consume it asynchronously
😎 1
j

Joey

12/11/2019, 6:35 AM
Got it working! Thank you very much!
Anyone that deals with the same use case. This is the final code:
Kotlin shared lib
Copy code
fun fetchUsersFromKtLib(callback: (String) -> Unit) {
        GlobalScope.launch {
            val response = client.get<JsonObject> { url("$baseUrl/heartbeat.json") }
            val listOfUsers = response.keys.iterator()
            listOfUsers.forEach {
                callback(it)
            }
        }
    }
Kotlin class inside old java project
Copy code
fun fetchUsers(listFromAndroid: ArrayList<String>) {
    val api = HeartbeatApi()
    return api.fetchUsersFromKtLib {
        listFromAndroid.add(it)
    }
}
Big thanks to @yshrsmz
👍 1
m

marstran

12/11/2019, 12:24 PM
You could also just return the future:
Copy code
fun fetchUsersFromKtLib(): CompletableFuture<List<String>> {
    val api = HeartbeatApi()
    return GlobalScope.future {
      api.fetchUsers()  
    }
}
j

Joey

12/13/2019, 12:36 AM
Where should i use this? In my android project? Cant seem to find
CompletableFuture
@marstran
m

marstran

12/13/2019, 12:39 AM
Hmm, doesn’t
GlobalScope.future
return a
CompletableFuture
?
j

Joey

12/13/2019, 12:42 AM
Nevermind found the correct plugin. My
api.fetchUsers()
should return the list of string right?
m

marstran

12/13/2019, 12:43 AM
Yes
j

Joey

12/13/2019, 12:43 AM
Will try this and get back to you 😄