Hi guys, i have this function inside my kotlin sha...
# multiplatform
j
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
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
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
You could also just return the future:
Copy code
fun fetchUsersFromKtLib(): CompletableFuture<List<String>> {
    val api = HeartbeatApi()
    return GlobalScope.future {
      api.fetchUsers()  
    }
}
j
Where should i use this? In my android project? Cant seem to find
CompletableFuture
@marstran
m
Hmm, doesn’t
GlobalScope.future
return a
CompletableFuture
?
j
Nevermind found the correct plugin. My
api.fetchUsers()
should return the list of string right?
m
Yes
j
Will try this and get back to you 😄