Hi everyone! I'm currently working with Coroutines...
# android
p
Hi everyone! I'm currently working with Coroutines, and I'm wondering if it's a good approach to pass a
Job
to a repository's constructor, especially to access it inside a ViewModel (and being able to cancel it)?
Copy code
class UserRepository(private val service: GithubService,
                     val job: Job)
Copy code
class SearchUserViewModel(private val repository: UserRepository): ViewModel() {

    private fun cancelJob() {
        repository.job.cancel()
    }
}
g
You can use Job as lifecycle handler of course, but what is your use case? Usually repositories shouldn't have any predefined Job, instead code that uses repository should manage lifecyle of request (which suspend function)
Also Job is disposable primitive, and it may be not really good to use it for such use case
p
Thanks for your answer. Actually, I'm using `PageKeyedDataSource`and I'm trying to add a network task inside it using a coroutine: https://gist.github.com/PhilippeBoisney/d55e50649b1d8aab7f2aaff36929bbcd
k
I'd suggest exposing suspending functions from the repo instead...
p
@kenkyee This was my first thought. And I'll return
Job
from this suspending functions?
k
Return the result... Caller maintains job
g
+1 to @kenkyee This is what I meant above, repository just exposes suspend functions, management of lifecyle should happen on side of caller. But even in this case repository still can control lifecycle under the hood (should request be cancelled or continue and cache result)
Returning job/deferred from method is not recommended practice, just return result
p
Thanks both of you @gildor @kenkyee. I implemented your recommendations here: https://gist.github.com/PhilippeBoisney/92ac4c853d5dd090c1ecb4e161564ba9 Everything's ok with this implementation?
k
Seeing a job in any of that code is weird to me.
p
@kenkyee How should I manage the job? Because I have to cancel it when user starts typing.
@gildor Do you think my actual implementation is wrong? https://gist.github.com/PhilippeBoisney/92ac4c853d5dd090c1ecb4e161564ba9
k
In your activity or fragment
p
Why not inside the VM ?
k
In VM isn't bad either... It knows about lifecycles
p
Actually, this is what I'm doing. I pass the VM scope (uiScope) to my Datasource and cancel it when VM is destroyed. Aldo, I cancel job launched by Datasource when user starts typing. For now, it does the job pretty well 🙂