如何在MVVM体系结构中使用来自onActivityResult的数据?

时间:2020-01-07 16:09:04

标签: android kotlin mvvm android-recyclerview android-mvvm

如何在MVVM体系结构中使用onActivityResult中的数据?我需要向RecyclerView添加一个项目,该项目已订阅以从ViewModel接收数据。如何将数据从onActivityResult发送到ViewModel类,然后更新列表?如果我立即从onactivityresult方法向适配器添加数据,则不会发生任何事情。在这个问题上我需要任何帮助

活动类别:

class ContactsActivity : AppCompatActivity(), ContactsListener {
    private val TAG = "ContactsActivity"

    @Inject
    lateinit var factory: ViewModelProvider.Factory
    lateinit var contactsViewModel: ContactsViewModel


    companion object {
        const val ADD_CONTACT_REQUEST = 200
    }

    private lateinit var mAdapter: ContactsAdapter

    @SuppressLint("WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        toolbar_contacts.title = getString(R.string.contacts_toolbar_title)

        add_new_contact_btn.setOnClickListener {
            val intent = Intent(this@ContactsActivity, AddContactActivity::class.java)
            startActivityForResult(intent, ADD_CONTACT_REQUEST)
        }

        DaggerContactsActivity_ContactsComponent.create().inject(this@ContactsActivity)
        contactsViewModel = ViewModelProviders.of(this@ContactsActivity, factory).get(ContactsViewModel::class.java)
        contactsViewModel.getContactsList().observe(this@ContactsActivity, Observer {

            mAdapter = ContactsAdapter(this@ContactsActivity, it)
            recycler_contacts.layoutManager =
                LinearLayoutManager(applicationContext, OrientationHelper.VERTICAL, false)
            recycler_contacts.adapter = mAdapter
            recycler_contacts.setHasFixedSize(true)

            mAdapter.sortByName()

        })
    }

    // Dagger create
    @Component (modules = [ContactsModule::class])
    interface ContactsComponent {

        fun inject (activity: ContactsActivity)
    }

    @Module
    abstract class ContactsModule {

        @Binds
    abstract fun bindViewModelFactory(factory: ContactsViewModelFactory): ViewModelProvider.Factory
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
            if (resultCode == ADD_CONTACT_REQUEST && resultCode == RESULT_OK) {
                val firstName: String? = data?.getStringExtra(AddContactActivity.EXTRA_FIRST_NAME)
                val lastName: String? = data?.getStringExtra(AddContactActivity.EXTRA_LAST_NAME)
                val phone: String? = data?.getStringExtra(AddContactActivity.EXTRA_PHONE)
                val email: String? = data?.getStringExtra(AddContactActivity.EXTRA_EMAIL)
                val notes: String? = data?.getStringExtra(AddContactActivity.EXTRA_NOTES)

                val contacts = Contacts(firstName = firstName.toString(), lastName = lastName.toString(), phone = phone.toString(),
                    email = email.toString(), notes = notes.toString(), images = "")

                contactsViewModel.get(contacts = contacts)
            }
        }

    override fun setupContactsList(contactsList: ArrayList<Contacts>) {

        mAdapter.setupContacts(contactsList = contactsList)
    }
}

2 个答案:

答案 0 :(得分:2)

在MVVM体系结构中,您不需要使用Activity的onActivityResult交换数据。而是让目标Activity的UI绑定到ViewModel的LiveData,后者进一步指向由另一个Activity(通过其自己的ViewModel)更新的同一数据源(例如sqLite)。

答案 1 :(得分:0)

MVVM启用双向绑定。当您完成或清除已覆盖其onActivity结果的活动时,只需更新列表即可。

数据已在您先前的活动中订阅,其他活动更新列表后,它将立即获得更新。这两个活动将共享ViewModel。

通过共享实例https://www.google.com/url?sa=t&source=web&rct=j&url=https://github.com/android/architecture-components-samples/issues/29&ved=2ahUKEwjn0ZWEzvPmAhUxzDgGHXhuBUsQFjAAegQICRAE&usg=AOvVaw36xQIOfJIp4abIODjXrz6S

查看MVVM的工作情况