Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

571
Views
En Actividad/Fragmento, ¿Cómo obtener/esperar el valor de retorno de la operación de rutinas de ViewModel?

Siguiendo la demostración de codelab de Google ( enlace ), trato de refactorizar mi código a ViewModel + coroutines. Mi pregunta es, en lugar de simplemente insertar los datos ( código original ), quiero esperar el resultado de la operación de inserción, que debería devolver la identificación si la inserción tuvo éxito, luego hacer algo basado en el resultado. Así que ¿cómo se hace?

Actualmente, envío un método al método de inserción de ViewModel como devolución de llamada. Por supuesto, observar el ViewModel es otra opción. Pero, ¿hay alguna solución mejor?

Mi código actual:

Actividad del evento:

 viewModel.insert(Event("name"), { if (it == -1L) { Log.i("insert", "failure") } else { Log.i("insert", "success: $it") } })

Modelo de vista de evento:

 private val mEventDao: EventDao = AppDatabase.getDatabase(application).eventDao() private val mJob = Job() private val mScope = CoroutineScope(Dispatchers.Main + mJob) fun insert(event: Event, callback: (id: Long) -> Unit) { mScope.launch(Dispatchers.IO) { val result = try { // just for testing delay situation delay(5000) val id = mEventDao.insertEvent(event) id } catch (e: Exception) { -1L } withContext(Dispatchers.Main) { callback(result) } } }

Dao de evento:

 @Dao interface EventDao { fun insertEvent(event: Event): Long }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede agregar un objeto LiveData a EventViewModel , actualizarlo cuando finalice la inserción y suscribirse a él en Activity :

 class EventViewModel : ViewModel() { //... var insertionId = MutableLiveData<Long>() fun insert(event: String) { mScope.launch(Dispatchers.IO) { val result = try { // just for testing delay situation delay(5000) val id = mEventDao.insertEvent(event) id } catch (e: Exception) { -1L } insertionId.postValue(result) } } }

Y suscríbete en EventActivity :

 class EventActivity : AppCompatActivity() { lateinit var viewModel: EventViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this).get(EventViewModel::class.java) viewModel.insertionId.observe(this, android.arch.lifecycle.Observer { id -> // Use `id` for example to update UI. }) // ... viewModel.insert(Event("name")) } }
over 4 years ago · Santiago Trujillo Report

0

 suspend fun insert(data: String): String = suspendCoroutine { cont -> //put logic here cont.resume("Done") //if error use this cont.resumeWithException(Exception("Error")) }

Puedo eliminar la devolución de llamada en esta función con retorno y esperar el retorno

 fun insertData(){ GlobalScope.launch { val status = insert("This is Data!") if( status == "Done"){ }else{ } } }
over 4 years ago · Santiago Trujillo Report

0

Pero, ¿hay alguna solución mejor?

creo que hay

en androidx.lifecycle.*:2.2.0 alpha01 el liveData { . . . } , las funciones emit() están disponibles.

puede reescribir su código en viewModel así.

 fun insertData(event: String) = liveData { val id = mEventDao.insertEvent(event) emit(id) }

y en tu actividad obsérvala.

 viewModel.insertData("YourEvent").observe(this) { updateUi(id) }

no olvides cambiar tus métodos de Dao para suspend

 @Dao interface EventDao { suspend fun insertEvent(event: Event): Long }

Por cierto, en este momento, la última versión de datos en vivo es 2.2.0-rc03

 implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-rc03"

puede ver una mejor implementación en la documentación de Android: Use coroutines con LiveData

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!