ArrayList Is Empty Outside the Coroutine Scope

Viewed 65

I'm building a project based on Android MVVM Architecture. I wrote my own API to get the Ddta. The API returns an ArrayList of cloths. I use Retrofit for calling the API. The Repository class works fine and it returning the list from the API but the problem occurred in the ViewModel.

When I access the ArrayList inside a coroutine its works fine ( using coroutine because getClothList is a Suspend function inside the Repository class ) but I'm not able to access that ArrayList outside the scope of coroutine.

clothlist is empty outside the viewModelScope

View Model

class ClothViewModel(private val repository: ClothRepository) :ViewModel() {
    lateinit var clothList:ArrayList<ClothModel>
 init {
     viewModelScope.launch(Dispatchers.IO) {
      clothList = repository.getClothsList()
      Log.d("ClothList ->",clothList.toString())
     }
 }
     fun getData():ArrayList<ClothModel>{
         clothList = repository.clothsList
        Log.d("View Model ->",clothList.toString())
         return clothList
    }

}

Repository Class

class ClothRepository(private val clothService: ClothService) {

   val clothsList = ArrayList<ClothModel>()
     suspend fun getClothsList():ArrayList<ClothModel>{
         val result = clothService.getClothList()
         if (result?.body() != null) {
            clothsList.add(result.body()!!)
         }
       Log.d("Result ->",result.body().toString())
        return clothsList
     }
}

Main Activity

Since I'm not getting the List in viewModel I am unable to used it inside the mainActivity

class WelcomeScreen: AppCompatActivity() {
     var arrayList = ArrayList<ClothModel>()
    var arrayList1 = ArrayList<ClothModel>()
    lateinit var viewModel :ClothViewModel
    var state =1
    lateinit var firebaseAuth:FirebaseAuth
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dashboard)

        val clothService = ClothHelper.getInstance().create(ClothService::class.java)
        val clothRepository = ClothRepository(clothService)
        viewModel = ViewModelProvider(this,ClothViewModelFactory(clothRepository)).get(ClothViewModel::class.java)
        arrayList = viewModel.getData() //calling the viewModel function
        setupADapter()
    }
      fun setupADapter(){
           var list = listOf("Nike","Romans","CK","Jordan","Kizumik","Hishida")
           var recyclerView = findViewById<RecyclerView>(R.id.cloths)
             Log.d("Passing ->",arrayList1.toString())
            recyclerView.adapter = ClothViewAdapter(arrayList1)
            recyclerView.layoutManager = GridLayoutManager(applicationContext,2)
      }
}
0 Answers
Related