BoundService + LiveData + ViewModel best practice in new Android recommended architecture

后端 未结 5 1396
半阙折子戏
半阙折子戏 2020-12-12 15:06

I been struggling a lot thinking about where to place Android Services in the new Android recommended Architecture. I came up with many possible solutions, but I cannot make

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 15:33

    One way to avoid direct contact with an Android service while still being able to use it is through an interface object. This is part of the "I" for Interface Segregation in the acronym, SOLID. Here is a small example:

    public interface MyFriendlyInterface {
        public boolean cleanMethodToAchieveBusinessFunctionality();
        public boolean anotherCleanMethod();
    }
    
    public class MyInterfaceObject implements MyFriendlyInterface {
        public boolean cleanMethodToAchieveBusinessFunctionality() {
            BluetoothObject obj = android.Bluetooth.nastySubroutine();
            android.Bluetooth.nastySubroutineTwo(obj);
        }
    
        public boolean anotherCleanMethod() {
            android.Bluetooth.anotherMethodYourPresentersAndViewModelsShouldntSee();
        }
    }
    
    public class MyViewModel {
        private MyFriendlyInterface _myInterfaceObject;
    
        public MyViewModel() {
            _myInterfaceObject = new MyInterfaceObject();
            _myInterfaceObject.cleanMethodToAchieveBusinessFunctionality();
        }
    }
    

    Given the above paradigm, you are free to place your services in a package that's outside your packages that contain POJO code. There is no "right" location to put your services -- but there are definitely WRONG places to put them (e.g. where your POJO code goes).

提交回复
热议问题