I am implementing an MVVM Android architecture in which in the main application component ( MainActivity
), I listen to the ModelView
's LiveData
storage for any changes. However, in the following piece of code:
private final var viewModel:ScheduleViewModel = ViewModelProviders.of(this).get(ScheduleViewModel::class.java)
viewModel.getSchedule().observe(this, object:Observer<String> {
fun onChanged(feed:String){
}
})
I get the following error:
Required: Observer<in String!>
Found:
Below are my imports:
import android.os.Build
import android.os.Bundle
import android.util.Base64
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import androidx.viewpager.widget.ViewPager
import com.example.mvvmarchitecture.ui.main.TabsAdapter
import com.google.android.material.tabs.TabLayout
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
To fix that, replace Observer<String>
with Observer<in String>
.
But even easier, use a lambda instead of an anonymous object, so you don't have to worry about matching up the type:
viewModel.getSchedule().observe(this) { feed ->
//...
}
What does viewModel.getSchedule()
return? if your function is defined like this
fun getSchedule():MutableLiveData<String>(){
// your code
return liveDataOfString
}
this it should compile.
viewModel.getSchedule().observe(this, object :androidx.lifecycle.Observer<in String> {
override fun onChanged(t: String?) {
TODO("Not yet implemented")
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.