SplashActivity启动后立即查询数据库,并在MainActivity的ViewModel中进行订阅

问题描述 投票:0回答:1

我在Github中有以下项目:https://github.com/Ali-Rezaei/Contacts

我有一个启动画面活动。 Activity启动后,我想执行一个使用SharedViewModel完成的查询。这是我的存储库类:

@Singleton
class ContactsRepository
@Inject constructor() // Requires empty public constructor
{
    @Inject
    lateinit var context: Context

    @Inject
    lateinit var schedulerProvider: BaseSchedulerProvider

    fun queryDb(selection: String?, selectionArgs: Array<String>?) {
        val cursor = context.contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                PROJECTION,
                selection,
                selectionArgs,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE UNICODE ASC")
        return Observable.create(ObservableOnSubscribe<List<Contact>>
        { emitter -> emitter.onNext(ContactUtil.getContacts(cursor, context)) })
                .subscribeOn(schedulerProvider.io())
                .observeOn(schedulerProvider.ui())
                .doFinally { cursor?.close() }
    }
}

我想在MainActivity中观察LiveData。我有以下ViewModel:

class ContactsViewModel(
        private val repository: ContactsRepository)
    : ViewModel() {

    private val compositeDisposable = CompositeDisposable()

    private val _liveData = MutableLiveData<Resource<List<Contact>>>()
    val liveData: LiveData<Resource<List<Contact>>>
        get() = _liveData

    init {
        _liveData.value = Resource.Loading()
        showContacts(null, null)
    }

    fun showContacts(selection: String?, selectionArgs: Array<String>?) {
        repository.queryDb(selection, selectionArgs).subscribe {
            _liveData.postValue(Resource.Success(it))
        }.also { compositeDisposable.add(it) }
    }

    /**
     * Called when the ViewModel is dismantled.
     * At this point, we want to cancel all disposables;
     * otherwise we end up with processes that have nowhere to return to
     * using memory and resources.
     */
    override fun onCleared() {
        super.onCleared()
        compositeDisposable.clear()
    }

    /**
     * Factory for constructing MainViewModel with parameter
     */
    class Factory @Inject constructor(
            private val repository: ContactsRepository
    ) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(ContactsViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return ContactsViewModel(repository) as T
            }
            throw IllegalArgumentException("Unable to construct ViewModel")
        }
    }
}

ViewModel的init方法调用两次(一次在SplashActivity中,然后在MainActivity中),我该怎么做才能仅在SplashActivity中执行查询并在MainActivity中观察liveData?

android repository-pattern android-viewmodel
1个回答
0
投票

我认为sharedViewModel适合您的情况。我相信您可以从数据库中请求数据,将结果数据设置为LiveData对象,以便能够订阅其更改。这个sharedViewModel也将在您的MainActivity中初始化。您将订阅此liveData(在SplashScreen中初始化)。

希望此解决方案对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.