Kotlin syntax for LiveData observer?

前端 未结 3 1808
失恋的感觉
失恋的感觉 2021-01-01 10:05

I have the following bit of code in my HomeActivity to use LiveData.

override fun onCreate(savedInstanceState: Bundle?) {
    sup         


        
相关标签:
3条回答
  • 2021-01-01 10:28

    To omit the Observer { ... } part just add import androidx.lifecycle.observe and use it like this:

    this.viewModel.user.observe(this) { user: User? ->
        // ...
    }
    
    0 讨论(0)
  • 2021-01-01 10:39

    in Kotlin the Observer { } lambda gives you param it, you can rename it as you want and use. by default data will be available with it.something() etc...

    JAVA:

    ... new Observer {
      void onChanged(User user){
         user.something()
      }
    }
    

    KOTLIN

    ... object : Observer<User> {
       fun onChanged(user: User?){
            user.something()
       }
    }
    

    OR

    ... Observer {
       it.something()
    }
    

    you can rename it to whatever you want like

    ... Observer { myUser ->
       myUser.something()
    }
    
    0 讨论(0)
  • 2021-01-01 10:45

    This is called SAM Conversion, a concept that helps interacting with Java Single Abstract Method Interfaces like in your example.

    The following creates an implementation of Runnable, where the single abstract method is run():

    val runnable = Runnable { println("This runs in a runnable") }
    

    It’s described in the docs: https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions

    Alternatively, but more verbose, would be to use an object:

    val runnable2 = object : Runnable {
            override fun run() {
                println("This runs in a runnable")
            }
    }
    

    Both are examples of anonymous implementations of that interface. It's of course also possible to create a concrete subclass and instantiate it then.

    class MyRunnable : Runnable {
        override fun run() {
            println("This runs in a runnable")
        }
    }
    
    val runnable3 = MyRunnable()
    
    0 讨论(0)
提交回复
热议问题