Estoy construyendo un proyecto basado en Android MVVM Architecture. Escribí mi propia API para obtener el Ddta. La API devuelve una ArrayList de telas. Uso Retrofit para llamar a la API. La clase Repository funciona bien y devuelve la lista de la API, pero el problema ocurrió en ViewModel.
Cuando accedo a ArrayList dentro de una rutina , funciona bien (usando coroutine porque getClothList es una función Suspender dentro de la clase Repository), pero no puedo acceder a ArrayList fuera del alcance de coroutine.
la lista de ropa está vacía fuera de viewModelScope
Ver modelo
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 } }Clase de repositorio
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 } }Actividad principal
Como no obtengo la Lista en viewModel, no puedo usarla dentro de 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) } }