https://kotlinlang.org logo
#android
Title
# android
p

Philippe Boisney

01/11/2019, 8:15 AM
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

gildor

01/11/2019, 8:26 AM
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

Philippe Boisney

01/11/2019, 8:33 AM
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

kenkyee

01/11/2019, 11:36 AM
I'd suggest exposing suspending functions from the repo instead...
p

Philippe Boisney

01/11/2019, 11:52 AM
@kenkyee This was my first thought. And I'll return
Job
from this suspending functions?
k

kenkyee

01/11/2019, 11:54 AM
Return the result... Caller maintains job
g

gildor

01/11/2019, 9:44 PM
+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

Philippe Boisney

01/12/2019, 10:56 AM
Thanks both of you @gildor @kenkyee. I implemented your recommendations here: https://gist.github.com/PhilippeBoisney/92ac4c853d5dd090c1ecb4e161564ba9 Everything's ok with this implementation?
k

kenkyee

01/12/2019, 12:41 PM
Seeing a job in any of that code is weird to me.
p

Philippe Boisney

01/12/2019, 12:53 PM
@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

kenkyee

01/12/2019, 2:05 PM
In your activity or fragment
p

Philippe Boisney

01/12/2019, 2:09 PM
Why not inside the VM ?
k

kenkyee

01/12/2019, 5:59 PM
In VM isn't bad either... It knows about lifecycles
p

Philippe Boisney

01/12/2019, 6:31 PM
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 🙂