Jetpack-Lifecycle

概述:
Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments.
例1:
A common pattern is to implement the actions of the dependent components in the lifecycle methods of activities and fragments. However, this pattern leads to a poor organization of the code and to the proliferation of errors.
By using lifecycle-aware components, you can move the code of dependent components out of the lifecycle methods and into the components themselves.
说白了就是生命周期和UI Controller解耦
例2对比:
internal class MyLocationListener(

    private val context: Context,

    private val callback: (Location) -> Unit) {

fun start() {

    // connect to system location service

}



fun stop() {

    // disconnect from system location service

}}

class MyActivity : AppCompatActivity() {

private lateinit var myLocationListener: MyLocationListener



override fun onCreate(...) {

    myLocationListener = MyLocationListener(this) { location ->

        // update UI

    }

}



public override fun onStart() {

    super.onStart()

    myLocationListener.start()

    // manage other components that need to respond

    // to the activity lifecycle

}



public override fun onStop() {

    super.onStop()

    myLocationListener.stop()

    // manage other components that need to respond

    // to the activity lifecycle

}

}
Managing multiple components places a considerable amount of code in lifecycle methods, such as onStart() and onStop(), which makes them difficult to maintain.Moreover, there’s no guarantee that the component starts before the activity or fragment is stopped.
这样写需要手动维护myLocationListener的生命周期,很容易出问题。如果可以自动监控生命周期就好了

public override fun onStart() {

        super.onStart()

        Util.checkUserStatus { result ->

            // what if this callback is invoked AFTER activity is stopped?

            if (result) {

                myLocationListener.start()

            }

        }

    }

####LifeCycle

LifeCycle

有两个主要的概念来追踪组件的生命周期

  • Event

The lifecycle events that are dispatched from the framework and the Lifecycle class. These events map to the callback events in activities and fragments.

  • State

The current state of the component tracked by the Lifecycle object.

简单来说就是Event是用来传递lifecycle状态的通信管路,而State就是基站显示器。
在这里插入图片描述

LifecycleOwner 和 LifecycleObserver

LifecycleObserver是一个观察者的概念,他不是通过类实现的,而是通过@OnLifecycleEvent(evnent:Lifecycle.Event)注解标记自定义的函数来实现的。可以定义一个这样的Interface,实现了此接口的类就会在被注解标记的回调函数内接收到lifecycle改变的通知。
举例:

@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onLifecycleStateChanged(owner: LifecycleOwner, event: Lifecycle.Event)

而发射器pusher就是参数之一 LifecycleOwner,必须在UI Component使得发射器被注册。所有的Fragment和Activity都官方实现了LifeCyleOwner接口

/**
 * A class that has an Android lifecycle. These events can be used by custom components to
 * handle lifecycle changes without implementing any code inside the Activity or the Fragment.
 *
 * @see Lifecycle
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

所以官方UI组件可以直接得到ower然后手动让其被注册到LifecycleObserver中

Fragments and Activities in Support Library 26.1.0 and later already implement the LifecycleOwner interface.

这样就组成了观察者模式了

Components that implement LifecycleObserver work seamlessly with components that implement LifecycleOwner because an owner can provide a lifecycle, which an observer can register to watch.

lifecycle.addObserver(vModel)

看下官方的例子

internal class MyLocationListener(
        private val context: Context,
        private val lifecycle: Lifecycle,
        private val callback: (Location) -> Unit
) {

    private var enabled = false

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() {
        if (enabled) {
            // connect
        }
    }

    fun enable() {
        enabled = true
        if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            // connect if not connected
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() {
        // disconnect if connected
    }
}
自定义的生命周期

如果不想追随官方UI Controller的生命周期,而是自己定义一套生命周期

You can use the LifecycleRegistry class, but you need to forward events into that class

必须手动来标记生命周期的状态

class MyActivity : Activity(), LifecycleOwner {

    private lateinit var lifecycleRegistry: LifecycleRegistry

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleRegistry = LifecycleRegistry(this)
        lifecycleRegistry.markState(Lifecycle.State.CREATED)
    }

    public override fun onStart() {
        super.onStart()
        lifecycleRegistry.markState(Lifecycle.State.STARTED)
    }

    override fun getLifecycle(): Lifecycle {
        return lifecycleRegistry
    }
}
来自官方的建议—生命周期敏感组件的最佳实践
  • 不要用UI Controller来请求数据,要写data-driven的UI,依靠LiveData来做MVVM模式,如果View层过于复杂,请使用presenter来处理复杂的UI,这样看上去比较干净和有逼格。

  • ViewModel层不要引用任何View层的context,而且vm层没有请求数据的责任,你可以使用更合适的组件来获取数据,vm层的本质是连接data和UI。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值