javaandroiddragger

How can create a singleton class with mock data with dragger 2?


Hi I want know if is possible create a singleton with mockdata and with dragger

I know the standard code for do it without dragger 2

public class Singleton {
    private Singleton() { }

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public String getFoo() {
        return "bar";
    }
}

Here I know where to put the array list with the data for mock, but how can do it with dagger where is the setup function or similar for put the ArrayList with the data, and how can call.

Thanks


Solution

  • You just need to add a method in one of your modules and annotate it with @Singleton annotation. For example:

    @Module
    public class MyModule {
        @Provides
        @Singleton
        MockData provideMockData() {
           return new MockData(Arrays.asList("A", "B", "C"));
        }
    
        @Provides
        OtherClass provideOtherClass(MockData mockData) {
           return new OtherClass(mockData);
        }
    }
    
    public class MockData {
    
        private List<String> list;
    
        public MockData(List<String> list){
            this.list = list;
        }
    
        public List<String> getList() {
            return list;
        }
    }
    

    Check the section "Singletons and Scoped Bindings" in https://google.github.io/dagger/users-guide.html