Apache License 2.0

技术解读

以下内容由 GitRead 中文社区 编辑团队基于项目 README 与官方资料整理, 结合中文开发者的常见使用场景补充技术选型建议。具体以项目官方文档为准。

深度剖析 lyft/scoop:打造基于视图的模块化 Android 应用的微框架

项目背景与痛点

现代 Android 应用复杂度日益增加,开发者需要应对日益增多的模块和碎片化设备。模块化开发能够提升应用的可维护性和复用性,但如何高效地管理视图(View)成为了一个难题。lyft/scoop 通过引入微框架的方式,为视图基础的模块化 Android 应用开发提供了一套解决方案。这一框架重在优化视图层次之间的通信,简化状态管理,提升开发效率,使得开发者可以在构建复杂应用时更加游刃有余。

核心技术揭秘

技术架构分析

lyft/scoop 的核心设计思想基于视图基础的模块化,它通过简化状态管理来降低复杂度,实现模块间的松耦合。整个架构通过对视图通信的封装,实现了状态的集中管理和更新推送。

graph TD A[用户交互] --> B[View] B --> C{"ViewModel"} C -->|"状态更新"| D[View] C -->|"状态更新"| E[Data Layer] E -->|"数据反馈"| C C -->|"事件分发"| F[Business Logic] F -->|"结果反馈"| C

图中,用户通过界面进行操作,视图接收到该操作后,将请求传递给 ViewModel 进行业务逻辑处理。ViewModel 负责管理 View 的状态更新,同时也对接数据层和业务逻辑层,形成一个闭环的数据流。这种设计极大提升了事件处理的性能和状态管理的灵活性。

数据流与管理

lyft/scoop 强调事件中心模式,每个事件触发都通过 ViewModel 处理,形成一种中心化的状态管理方式。这种模式避免了直接的视图通信,增强了代码的模块化和可测试性。通过合理的数据流控制,框架能够在处理复杂用户交互时表现出良好的容错能力。

功能亮点与差异

相比其他框架,lyft/scoop 的杀手锏在于其特有的状态管理机制,不仅有利于开发阶段的状态跟踪,也便于后期的维护和扩展。相比于依赖复杂的视图层次,scoop 的视图通信机制能够在保持界面简洁的同时,增强了应用的性能。

此外,lyft/scoop 支持流畅的应用状态变化,利用集中化的状态管理,能够实现高效的状态更新和推送,从而提升用户体验。

应用场景与落地建议

在生产环境使用 lyft/scoop,开发者需要关注的是状态管理的复杂性。随着应用视图数目的增加,状态管理的复杂度也会相应增加,合理设计和划分 ViewModel 尤为重要。该框架非常适合大中型项目,特别是那些注重视图交互和状态管理的应用场景。

对于初创项目来说,lyft/scoop 提供了一个简洁且高效的起点,而在大型、成熟的应用中,框架的高度灵活性使得它能够应对更为复杂的业务逻辑。

综合评价

优点:

  • 简化状态管理,提升开发效率。
  • 强调模块化开发,提升应用的可维护性和复用性。
  • 高效的状态更新机制,优化用户体验。

缺点:

  • 对开发者的状态管理思路有一定要求。
  • 在处理大量视图的情况下,维护状态复杂度会提升。

总体来看,lyft/scoop 是一个为 Android 平台量身打造的,特别适用于高复杂度应用开发的框架。如果你的应用涉及大量的视图管理与状态变更,那么 lyft/scoop 无疑是一个值得考虑的选择。

简要分析

热度分
1187
价值分
642
活跃状态
归档

语言占比

Java
Shell

README

Deprecation Note

The open-source version of Scoop is no longer actively maintained and does not represent the version of Scoop currently being used internally at Lyft.

Scoop Build Status

Scoop is a micro framework for building view based modular Android applications.

What do I get?

  1. Router. Object that allows you to navigate between screens and maintain backstack.
  2. View controllers. A new building block that you will use instead of Activity and Fragments.
  3. Layouts. A new building block that you will use instead of Activity and Fragments.
  4. Scoops (“Scopes”). Hierarchical scopes that allows you organize your application dependencies and their lifespan.
  5. Transitions. Animations played between moving from one view to another. We provide a set of basic transitions such as sliding right, left, etc. Additionally, you are able to create your own custom transitions.

Our navigation is based on lightweight objects called Screen.

Screen is a meta data object that specifies which view controller or layout you want to show and optional data you want to pass to your view controller or layout. You can think of them as Android Intents with a much simpler API.

Screen screen = new MyScreen(new MyData("foo"));

router.goTo(screen);

The Screen class is extendable, and will provide you with the foundation for your navigation.


@ViewController(MyController.class)
public class MyScreen extends Screen {
}

We provide 5 primary navigation methods:

  1. goTo - Go to specified Screen and add it to the backstack.
  2. replaceWith - Go to specified Screen and replace the top of the backstack with it.
  3. replaceAllWith - Replace the backstack with a List of specified Screens, and navigate to the last Screen in the list.
  4. resetTo - Go to specified Screen and remove all Screens after it from the backstack. If the specified screen is not in the backstack, remove all and make this Screen the top of the backstack.
  5. goBack - Navigate to previous Screen.

Router does not render views. Router just emits an event that you can listen to in order to render the specified Screen. Within Scoop we provide the extensible view UIContainer that you can use to render view controllers and transitions.

ViewController

This class manages a portion of the user interface as well as the interactions between that interface and the underlying data. Similar to an activity or a fragment, ViewController requires you to specify the layout id and has lifecycle methods. However, a ViewController lifecycle only has two states: “attached” and “detached”.

You can also use view binders like Butterknife. So you don’t need to explicitly call ButterKnife.bind/unbind.


@ViewController(MyController.class)
public class MyScreen extends Screen {
}
public class MyController extends ViewController {

    @Override
    protected int layoutId() {
        return R.layout.my;
    }

    @Override
    public void onAttach() {
        super.onAttach();
    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

    @OnClick(R.id.do_smth)
    public void doSomething() {

    }
}

The big difference from Android fragments and activities is that in Scoop we don’t keep the ViewController in memory after it was detached. Whenever you move to a new Screen the ViewController detaches and is disposed together with the view.

Layout

A Layout annotation can be used similarly to ViewController annotation, and can accomplish the same goals. However, there is a higher degree of coupling between the controller and the view in this approach, so this implementation is generally not recommended.

@Layout(R.layout.my)
public class MyScreen extends Screen {
}
public class MyView extends FrameLayout {

    public LayoutView(Context context, AttributeSet attrs) {
      super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
      super.onAttachedToWindow();

      if (isInEditMode()) {
        return;
      }
    }

    @OnClick(R.id.do_smth)
    public void doSomething() {

    }
}

Scoops

Scoop’s namesake is the word “scope”. You can think of app scopes as ice cream scoops: going deeper in the navigation stack is an extra scoop on the top with another flavor.

Primary purpose of scoops is providing access to named services. When you create a scoop you have to specify its parent (except root) and services.

Scoop rootScoop = new Scoop.Builder("root")
        .service(MyService.SERVICE_NAME, myService)
        .build();

Scoop childScoop = new Scoop.Builder("child", rootScoop)
        .service(MyService.SERVICE_NAME, myService2)
        .service(OtherService.SERVICE_NAME, otherService)
        .build();

Internally, when trying to find a service within scoop, scoop will first try to find the service within itself. If the service is not within itself, scoop will iteratively go up in its scoop heirarchy to try to find the service.

MyService service = childScoop.findService(MyService.SERVICE_NAME);

When a scoop is no longer needed you can destroy it, which will remove references to all its services and invoke destroy for all children.

childScoop.destroy();

You are only required to create the root scoop manually. All child scoops will be created by Router whenever you advance in navigation. Created child scoops will be destroyed whenever you navigate to a previous item in the backstack.

To control child scoop creation you should extend ScreenScooper class. By default ScreenScooper only adds Screen to each child scoop.

Instead of adding individual services to your scoops, we recommend implementing dagger integration. In this case the only added service will be the dagger injector.

public class DaggerScreenScooper extends ScreenScooper {

    @Override
    protected Scoop addServices(Scoop.Builder scoopBuilder, Screen screen, Scoop parentScoop) {
        DaggerInjector parentDagger = DaggerInjector.fromScoop(parentScoop);

        DaggerModule daggerModule = screen.getClass().getAnnotation(DaggerModule.class);

        if(daggerModule == null) {
            return scoopBuilder.service(DaggerInjector.SERVICE_NAME, parentDagger).build();
        }

        DaggerInjector screenInjector;

        try {
            Object module = daggerModule.value().newInstance();
            screenInjector = parentDagger.extend(module);
        } catch (Throwable e) {
            throw new RuntimeException("Failed to instantiate module for screen: " + screen.getClass().getSimpleName(), e);
        }

        return scoopBuilder
                .service(DaggerInjector.SERVICE_NAME, screenInjector).build();
    }
}

Transitions

Transitions are animations played between moving from one ViewController to another. Within Scoop we provide the following built in transitions:

  1. Backward slide
  2. Forward slide
  3. Downward slide
  4. Upward slide
  5. Fade

To apply a transition you have to specify it for your ViewController by overriding enterTransition()/exitTransition() methods.

public class MyController extends ViewController {

    @Override
    protected ScreenTransition enterTransition() {
        return new ForwardSlideTransition();
    }

    @Override
    protected ScreenTransition exitTransition() {
        return new BackwardSlideTransition();
    }

    ...
}

If a transition is not specified, views will be swapped instantly.

You can also implement custom transitions by implementing the ScreenTransition interface.

public class AutoTransition implements ScreenTransition {

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void translate(final ViewGroup root, final View from, final View to, final TransitionListener transitionListener) {

        Scene toScene = new Scene(root, to);

        android.transition.AutoTransition transition = new android.transition.AutoTransition();

        transition.addListener(new Transition.TransitionListener() {
            @Override
            public void onTransitionEnd(Transition transition) {
                transitionListener.onTransitionCompleted();
            }

            @Override
            public void onTransitionCancel(Transition transition) {
                transitionListener.onTransitionCompleted();
            }
            ...
        });

        TransitionManager.go(toScene, transition);
    }
}

Samples

  • Basics - App that showcases the basics of Scoop (navigation, parameter passing, dependency injection)
  • Micro Lyft - advanced sample based on Lyft’s public api to showcase real world usage [COMING SOON].

Questions

For questions please use GitHub issues. Mark the issue with the “question” label.

Download

compile 'com.lyft:scoop:0.4.2'

Snapshots of development version are available in Sonatype’s snapshots repository.

License

Copyright (C) 2015 Lyft, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Special Thanks

评论

暂无评论