I'm working on a codebase with both Java and Kotli...
# android
j
I'm working on a codebase with both Java and Kotlin code, i introduced Kotlin coroutines to help in running background tasks, however i have a function in my repository marked with the keyword suspend and i call it from an Intent Service that is written in java to sync local db with remote. However i can only call a suspend function from another suspend function or a coroutine builder. I three options in mind: Option 1 Use GlobalScope.launch(Dispatchers.IO) on the function so that i can call it from the Intent Service. However GloablScope is not highly recommended in the android context. Option 2 Make my repository extend Coroutine Scope, create a public function called onCleared that cancels job, then call this function when the service onDestroyed method is called or when the view model onCleared method is called. This option is to try and cancel any running operations. Option 3 Use the viewmodel scope to launch the coroutine in the repository, then call the viewmodel from the service, however the viewmodel should only be limited to an activity or fragment. Option 4 Refactor the intent service to Kotlin and use coroutines
s
Option 4 seems like the most realistic. If you have some code in Kotlin and some in Java then you must be looking to make a full switch at some point. That makes option 4 the cleanest overall.
3
n
Yeah.. but if your intentService is wayy to complex to refactor from Java to Kotlin, you can just create intentServiceHelper class in Kotlin and handle repository call in the helper class. That way, you are extending it instead of refactoring. But in a long run, definitely refactor seems more like a correct way to go.
j
@Nirmal The helper
Copy code
class CoroutineIntentServiceHelper @Inject constructor(private val farmerRepository: FarmerRepository) : CoroutineScope{
    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = job + <http://Dispatchers.IO|Dispatchers.IO>

    fun postUnsyncedFarmers() = launch {
        farmerRepository.postUnsyncedFarmers()
    }

    fun clear(){
        job.cancel()
    }
}
In the intent service;
Copy code
coroutineIntentServiceHelper.postUnsyncedFarmers();

//When the service is destroyed, cancell any running operations
@Override
public void onDestroy() {
      coroutineIntentServiceHelper.clear();
}
s
I think when you have to write helper classes to go between languages, you are better off just converting.
n
I agree. If its just too complex or want to do some thing quick, may be helper class would work, but its better to just convert.