android - how to use liveData without viewModel class

Viewed 2741

I want to use livedata with nont activity class and I want to observe the changes in that class .

this is my code:

class Drawer(_activity: Activity) : NavigationView.OnNavigationItemSelectedListener {
private val activity: Activity
private val drawerLayout: DrawerLayout
private val nav_view: NavigationView

private val _openDrawer = MutableLiveData<Boolean>()
val openDrawer: LiveData<Boolean>
    get() = _openDrawer

init {
    activity = _activity
    drawerLayout = activity.findViewById(R.id.drawer_layout)
    nav_view = activity.findViewById(R.id.drawer_nav_view)
}

fun displayDrawerIcon() {
    val drawerIcon: ImageView = activity.findViewById(R.id.img_toolbar_drawer)
    drawerIcon.visibility = View.VISIBLE
    drawerIcon.setOnClickListener { _openDrawer.value = true }
}

as you can see in above example ,when the drawer item is selected , I set a value to livedata and I want to notify on changes in my activity . this is the code in my activity class :

drawer.openDrawer.observe(this, Observer {

    })

but it shows me an error on the "this" : enter image description here

a question , should I use viewModel with livedata and it's wrong to use livedata without a viewModel or I'm doing something wrong ?

this is my gradle :

  implementation 'androidx.appcompat:appcompat:1.1.0-alpha04'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

implementation "androidx.recyclerview:recyclerview:1.0.0-beta01"
implementation "androidx.cardview:cardview:1.0.0-beta01"
implementation "com.google.android.material:material:1.0.0-beta01"


def lifecycle_version = "2.2.0-alpha01"
def ViewModelScope="2.1.0-beta01"
def moshiVersion = "1.8.0"
def retrofit2_version = "2.6.0"
def okhttp3_version = "3.12.0"
def kotlinCoroutineVersion = "1.0.1"
def room_version = "2.1.0-alpha04"
def dagger_version="2.24"
def glide_version="4.10.0"


//lifecycle
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" //
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$ViewModelScope"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
0 Answers
Related