Solution 1 :
Well if you want to share a flow from your Worker class to your app, you can use room database for that, for example let’s say that you want to share a Flow<List> from your Worker
to achieve that you need to follow these steps:
- First create a
Book Entity
in your room database. - Second add a function in your
Dao
that returns a Flow<List>. - Third collect that flow in your app (view model, repository, fragment…).
- Finally in your
Worker
keep adding books to your room database.
With these 4 steps you will be able to collect data from Worker
in any other class.
I hope that my answer was clear and helpful 😀
Problem :
I’m facing following problem: there’s my class which inherits CoroutineWorker
. Logic of this worker is complicated enough, in fact doWork()
calls bunch of other routines inside and catches (collect
) results of several StateFlow
s, like:
override suspend fun doWork(): Result {
//blah-blah
withContext(Dispatchers.Default) {
_scanResultState.collectLatest {
//blah-blah
}
}
return ...
}
Questions:
- Can I somehow return/put collected
StateFlow
values (values are simple primitive objects) toWorker.Result
? - Or as an option – how could I listen/collect those
StateFlow
in other class – outside of myWorker
?
Since, Worker
class instantiated by WorkManager
– I can’t have a reference to concrete instance of Worker
. E.g. in Service
I could have reference to instance through bound Services, but in case of WorkManager looks like it’s impossible.
Any ideas?
Comments
Comment posted by DarShan
1. If the values are primitive, you can put them in
Comment posted by Barmaley
How can I return a value from inside of ‘collect’? I tried but couldn’t…
Comment posted by Barmaley
Looks workable, but ugly 🙂 I’d prefer to have more nice solution
Comment posted by Mo Coding
That’s the only way to do it :D, and in some cases when you need to keep that data in room database it’s a good solution.
Comment posted by Barmaley
Maybe,
Comment posted by Mo Coding
Well, if you just want to share a boolean or int or any simple type, DataStore is more feasible but if you want to share an object or a list of an object you can’t do it with DataStore.