Exactly this below code I want to use in my existing Java class, because write now it is not possible to convert entire class in Kotlin:
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.tasksEvent.collect { event ->
}
}
Kindly suggest the best approach. I know AsyncTask is deprecated.
Since lifecycleScope it's an extension function you need to call it with a different syntax from java:
LifecycleOwnerKt.getLifecycleScope(this)
Where this is your activity, fragment, etc.
After that you can pass that lifecycleScope to a new kotlin class and return the result with a callback, something like this:
KotlinClass.kt
class KotlinClass {
fun useCoroutineScope(
scope: LifecycleCoroutineScope,
callback: (SomeType) -> Unit
) {
scope.launchWhenCreated {
// Computation code...
callback(someValue)
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With