I have the following ViewModel
class MainViewModel @Inject constructor(private val mainRepository: MainRepository) : ViewModel(){
private var _user: LoggedInUser? = null
val allProjects: MutableLiveData<Array<Project>> = MutableLiveData()
fun setUser(loggedInUser: LoggedInUser){
_user = loggedInUser
getAllProjects()
}
fun getAllProjects(): LiveData<Array<Project>> {
println("MVM: In get all projects")
allProjects.value = mainRepository.getAllProjects(_user!!.token).value
println(" AFTER ${Arrays.toString(allProjects.value)}")
return mainRepository.getAllProjects(_user!!.token)
}
}
When I call setUser()
or getAllProjects()
the data does not get set. And in the After print statement I get null.
MainRepository
:
@Singleton
class MainRepository {
var job: CompletableJob? = null
fun getAllProjects(auth: String): LiveData<Array<Project>> {
println("REPO: In get all projects")
val data = MutableLiveData<Array<Project>>()
var job = Job()
job?.let {theJob ->
CoroutineScope(context = Dispatchers.IO + theJob).launch {
val projects = RetrofitBuilder.apiService.getAllProjects("Bearer " + auth)
withContext(Dispatchers.Main){
data.value = projects
println("INSIDE: ${Arrays.toString(projects)}")
theJob.complete()
}
}
println("getAllProjects DATA: ${Arrays.toString(data.value)}")
return data
}
}
fun cancelJobs(){
job?.cancel()
}
}
Here the INSIDE print statement prints out the data, while the getAllProjects DATA
prints null. In my activity I both have an observer that is trigger when the LiveData is changed and that also prints out null (I did this to debug without worrying of async calls) and I also have button that prints out the live data -- that is also null.
Anyone know how I can get this to work?