Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Inside Architecture Components

Inside Architecture Components

Lifecycle, LiveData, ViewModelの使いかたとその仕組みについて

kobito-kaba

February 07, 2018
Tweet

More Decks by kobito-kaba

Other Decks in Programming

Transcript

  1. 例題 class NetworkStateReceiver(private val callback : (NetworkInfo?) -> Unit) :

    BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val conn = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return callback(conn.activeNetworkInfo) } }
  2. class MainActivity : AppCompatActivity() { private lateinit var receiver: NetworkStateReceiver

    private lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById(R.id.textView) receiver = NetworkStateReceiver { if (it != null && it.isConnected) { textView.text = "online" } else { textView.text = "offline" } } } 例題 override fun onResume() { super.onResume() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(receiver, filter) } override fun onPause() { super.onPause() unregisterReceiver(receiver) } }
  3. class MainActivity : AppCompatActivity() { private lateinit var receiver: NetworkStateReceiver

    private lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById(R.id.textView) receiver = NetworkStateReceiver { if (it != null && it.isConnected) { textView.text = "online" } else { textView.text = "offline" } } } 例題 override fun onResume() { super.onResume() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(receiver, filter) } override fun onPause() { super.onPause() unregisterReceiver(receiver) } } Activityのロジックと混在する
  4. class MainActivity : AppCompatActivity() { private lateinit var receiver: NetworkStateReceiver

    private lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById(R.id.textView) receiver = NetworkStateReceiver { if (it != null && it.isConnected) { textView.text = "online" } else { textView.text = "offline" } } } 例題 override fun onResume() { super.onResume() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(receiver, filter) } override fun onPause() { super.onPause() unregisterReceiver(receiver) } } Activityのロジックと混在する Activity / Fragmentごとに書くの嫌
  5. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { callback(Connectivity.ONLINE) } else { callback(Connectivity.OFFLINE) } } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 使いかた @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun release() { activity = null } } enum class Connectivity { OFFLINE, ONLINE }
  6. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { 〜〜 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 〜〜 } 使いかた
  7. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { 〜〜 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 〜〜 } 使いかた
  8. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { 〜〜 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 〜〜 } 使いかた 普通はこうする。作るの楽だから。 interface LifecycleObserver { fun onCreate() {} fun onResume() {} fun onPause() {} fun onDestroy() {} // ... }
  9. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { 〜〜 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 〜〜 } 使いかた
  10. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { 〜〜 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 〜〜 } 使いかた 要らないイベント省略可
  11. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { 〜〜 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 〜〜 } 使いかた 要らないイベント省略可 メソッド名 = 処理内容
  12. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { 〜〜 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 〜〜 } 使いかた 要らないイベント省略可 メソッド名 = 処理内容 複数のメソッドに分割
  13. 使いかた class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?)

    { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textView) val networkObservable = NetworkObservable(this) { if (it == Connectivity.ONLINE) { textView.text = "online" } else { textView.text = "offline" } } lifecycle.addObserver(networkObservable) } }
  14. 余談 class FooObservable() : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun fooMethod() { 〜〜 }

    } class FooObservableAdapter(private val target : FooObservable) : LifecycleObserver { fun onResume() { target.fooMethod() } }
  15. @Override public void addObserver(@NonNull LifecycleObserver observer) { State initialState =

    mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); 〜〜 } Lifecycleを追え
  16. @Override public void addObserver(@NonNull LifecycleObserver observer) { State initialState =

    mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); 〜〜 } Lifecycleを追え
  17. static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer,

    State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } } Lifecycleを追え
  18. static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer,

    State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } } Lifecycleを追え
  19. static GenericLifecycleObserver getCallback(Object object) { 〜〜 int type = getObserverConstructorType(klass);

    if (type == GENERATED_CALLBACK) { 〜〜 return アノテーションプロセッサを使った場合用のクラス } return リフレクションを使う場合のクラス } Lifecycleを追え
  20. public class SupportActivity extends Activity implements LifecycleOwner { 〜〜 @Override

    @SuppressWarnings("RestrictedApi") protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } 〜〜 } Lifecycleを追え
  21. public class ReportFragment extends Fragment { @Override public void onActivityCreated(Bundle

    savedInstanceState) { dispatch(Lifecycle.Event.ON_CREATE); } 〜〜 } Lifecycleを追え
  22. Lifecycleを追え public class ReportFragment extends Fragment { private void dispatch(Lifecycle.Event

    event) { 〜〜 if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } }
  23. class NetworkObservable(private var activity: Activity?, private val callback : (Connectivity)

    -> Unit) : LifecycleObserver { private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { callback(Connectivity.ONLINE) } else { callback(Connectivity.OFFLINE) } } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } 使いかた @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun release() { activity = null } }
  24. class NetworkObservable(private var activity: Activity?) : LifecycleObserver { private val

    connectivity = MutableLiveData<Connectivity>() private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { connectivity.postValue(Connectivity.ONLINE) } else { connectivity.postValue(Connectivity.OFFLINE) } } fun getConnectivity() : LiveData<Connectivity> = connectivity @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } 使いかた @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun release() { activity = null } } }
  25. class NetworkObservable(private var activity: Activity?) : LifecycleObserver { private val

    connectivity = MutableLiveData<Connectivity>() private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { connectivity.postValue(Connectivity.ONLINE) } else { connectivity.postValue(Connectivity.OFFLINE) } } fun getConnectivity() : LiveData<Connectivity> = connectivity 〜〜 } 使いかた
  26. class NetworkObservable(private var activity: Activity?) : LifecycleObserver { private val

    connectivity = MutableLiveData<Connectivity>() private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { connectivity.postValue(Connectivity.ONLINE) } else { connectivity.postValue(Connectivity.OFFLINE) } } fun getConnectivity() : LiveData<Connectivity> = connectivity 〜〜 } 使いかた
  27. class NetworkObservable(private var activity: Activity?) : LifecycleObserver { private val

    connectivity = MutableLiveData<Connectivity>() private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { connectivity.postValue(Connectivity.ONLINE) } else { connectivity.postValue(Connectivity.OFFLINE) } } fun getConnectivity() : LiveData<Connectivity> = connectivity 〜〜 } 使いかた
  28. class NetworkObservable(private var activity: Activity?) : LifecycleObserver { private val

    connectivity = MutableLiveData<Connectivity>() private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { connectivity.postValue(Connectivity.ONLINE) } else { connectivity.postValue(Connectivity.OFFLINE) } } fun getConnectivity() : LiveData<Connectivity> = connectivity 〜〜 } 使いかた
  29. class NetworkObservable(private var activity: Activity?) : LifecycleObserver { private val

    connectivity = MutableLiveData<Connectivity>() private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { connectivity.postValue(Connectivity.ONLINE) } else { connectivity.postValue(Connectivity.OFFLINE) } } fun getConnectivity() : LiveData<Connectivity> = connectivity 〜〜 } 使いかた
  30. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    〜〜 val observable = NetworkObservable(this) observable.getConnectivity().observe(this, Observer<Connectivity> { if (it == Connectivity.ONLINE) { textView.text = "online" } else { textView.text = "offline" } }) lifecycle.addObserver(observable) } } 使いかた
  31. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    〜〜 val observable = NetworkObservable(this) observable.getConnectivity().observe(this, Observer<Connectivity> { if (it == Connectivity.ONLINE) { textView.text = "online" } else { textView.text = "offline" } }) lifecycle.addObserver(observable) } } 使いかた
  32. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    〜〜 val observable = NetworkObservable(this) observable.getConnectivity().observe(this, Observer<Connectivity> { if (it == Connectivity.ONLINE) { textView.text = "online" } else { textView.text = "offline" } }) lifecycle.addObserver(observable) } } 使いかた
  33. LiveDataを追え class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?)

    { 〜〜 val observable = NetworkObservable(this) observable.getConnectivity().observe(this, Observer<Connectivity> { if (it == Connectivity.ONLINE) { textView.text = "online" } else { textView.text = "offline" } }) lifecycle.addObserver(observable) } }
  34. LiveData public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {

    〜〜 LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer); ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper); 〜〜 owner.getLifecycle().addObserver(wrapper); }
  35. LiveData public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {

    〜〜 LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer); ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper); 〜〜 owner.getLifecycle().addObserver(wrapper); }
  36. LiveData public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {

    〜〜 LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer); ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper); 〜〜 owner.getLifecycle().addObserver(wrapper); }
  37. LiveData class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver { 〜〜 @Override

    boolean shouldBeActive() { return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED); } 〜〜 }
  38. 使いかた class NetworkObservable(private var activity: Activity?, private val callback :

    (Connectivity) -> Unit) : LifecycleObserver { private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { callback(Connectivity.ONLINE) } else { callback(Connectivity.OFFLINE) } } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) activity?.registerReceiver(receiver, filter) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver() { activity?.unregisterReceiver(receiver) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun release() { activity = null } } enum class Connectivity { OFFLINE, ONLINE }
  39. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textView) val viewModel = ViewModelProviders.of(this).get(NetworkViewModel::class.java) viewModel.connectivity.observe(this, Observer<Connectivity> { when(it) { Connectivity.ONLINE -> textView.text = "online" Connectivity.OFFLINE -> textView.text = "offline" } }) val networkObservable = NetworkObservable(this) { viewModel.connectivity.postValue(it) } lifecycle.addObserver(networkObservable) } } 使いかた
  40. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textView) val viewModel = ViewModelProviders.of(this).get(NetworkViewModel::class.java) viewModel.connectivity.observe(this, Observer<Connectivity> { when(it) { Connectivity.ONLINE -> textView.text = "online" Connectivity.OFFLINE -> textView.text = "offline" } }) val networkObservable = NetworkObservable(this) { viewModel.connectivity.postValue(it) } lifecycle.addObserver(networkObservable) } } 使いかた
  41. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textView) val viewModel = ViewModelProviders.of(this).get(NetworkViewModel::class.java) viewModel.connectivity.observe(this, Observer<Connectivity> { when(it) { Connectivity.ONLINE -> textView.text = "online" Connectivity.OFFLINE -> textView.text = "offline" } }) val networkObservable = NetworkObservable(this) { viewModel.connectivity.postValue(it) } lifecycle.addObserver(networkObservable) } } 使いかた